1.json串转化成xml文件
p=[{"name":"tom","age":30,"sex":"男"}, {"name":"lily","age":23,"sex":"女"}, {"name":"joy","age":40,"sex":"女"}]
import xml.dom.minidom
doc=xml.dom.minidom.Document()
root=doc.createElement("class")
root.setAttribute("no","1")
doc.appendChild(root)
for i in p:
student=doc.createElement("student")
name=doc.createElement("name")
name.appendChild(doc.createTextNode(i["name"]))
age=doc.createElement("age")
age.appendChild(doc.createTextNode(str(i["age"])))
sex=doc.createElement("sex")
sex.appendChild(doc.createTextNode(i["sex"]))
student.appendChild(name)
student.appendChild(age)
student.appendChild(sex)
root.appendChild(student)
fp=open(r"e:abc ew1.xml","w")
doc.writexml(fp,indent="",addindent=" ",newl=" ",encoding="utf-8")
2.xml文件转换成json串:
方法一:
from xml.dom.minidom import parse
DOMTree=parse(r"e:abc ew1.xml")
root=DOMTree.documentElement
print root
list_students=[]
for student in root.getElementsByTagName("student"):
d={}
for i in range(1,len(student.childNodes)-1,2):
d[student.childNodes[i].tagName]=student.childNodes[i].childNodes[0].data
list_students.append(d)
print list_students
方法二:
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
tree=ET.ElementTree(file="e:\abc\new1.xml")
root=tree.getroot
print root
list_students=[]
for elem in tree.iter(tag="student"):
d={}
for e in tree.iterfind("student/"):
d[e.tag]=e.text
list_students.append(d)
print list_students