from lxml import etree
def dictlist(node):
res = {}
res[node.tag] = []
xmltodict(node,res[node.tag])
reply = {}
reply[node.tag] = {'value':res[node.tag],'attributes':node.attrib}
return reply
def xmltodict(node,res):
rep = {}
if len(node):
#n = 0
for n in list(node):
rep[node.tag] = []
value = xmltodict(n,rep[node.tag])
if len(n):
value = {'value':rep[node.tag],'attributes':n.attrib}
#print value
res.append({n.tag:value})
else :
#print rep[node.tag][0]
res.append(rep[node.tag][0])
else:
value = {}
value = {'value':node.text,'attributes':node.attrib}
#print value
res.append({node.tag:value})
return
def fromstring(strdict=None):
root = etree.fromstring(strdict)
return dictlist(root)
def parse(filename=None):
tree = etree.parse(filename)
return dictlist(tree.getroot())
def main():
tree = etree.parse('test.xml')
print tree
res = dictlist(tree.getroot())
print res
def dict2xml(d):
from xml.sax.saxutils import escape
def unicodify(o):
if o is None:
return u'';
return unicode(o)
lines = ["<?xml version=/"1.0/" encoding=/"utf-8/"?>"]
def addDict(node, offset):
for name, value in node.iteritems():
if name == "attributes":
strqq = lines[len(lines)-1]
index = strqq.find(u"
strqq = strqq[index+1:len(strqq)-1]
for x,y in value.iteritems():
strqq = strqq + u" " *4 + u"%s='%s'"%(x,y)
lines[len(lines)-1] = u" " * index + u""%(strqq)
else:
if isinstance(value, dict):
lines.append(offset + u"" % name)
addDict(value, offset + u" " * 4)
lines.append(offset + u"%s>" % name)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
addDict(item, offset + u" " * 4)
else:
lines.append(offset + u"%s%s>" % (name, escape(unicodify(item)), name))
else:
if value != "":
pass
addDict(d, u"")
lines.append(u"")
return u"/n".join(lines)
#if __name__ == '__main__' :
# main()
test 就不帮大家写了