from xml.etree.ElementTree import ElementTree
from lxml import etree ##的下载安装lxml的包
Class XMLData:
def readXML(self,xml_file):##xml_file为xml文件名
doc = etree.ElementTree(file=xml_file)
root = doc.getroot();
items = root.getchildren();
listctrldata = {};
index = 1;
for item in items:
itemchild = item.getchildren();
arr_name = [];
fot ic in intemchild:
if ic.text = None:
ic.text=''
arr_name.append(ic.text)
listctrldata[index] = arr_name
index+=1
return listctrldata
##修改xml
def write(self,xml_file,listctrldata):
doc = etree.ElementTree(file=xml_file)
root = doc.getroot()
listlen = len(listctrldata)
itemlen = len(root.getchilddren())
if itemlen > listlen:
for more in range(itemlen-listlen):
root.remove(root.getchildren()[0])
elif itemlen < listlen:
for less in range(listlen-itemlen):
item = root.getchildren()[0]
itemadd = etree.Element(item.tag)
for it in item.getchildren():
itadd = stree.Element(it.tag)
itemadd.append(itadd)
root.append(itemadd)
else:pass
j=1
for item in root.getchildren():
itemchild = item.getchildren()
k = 0
for ic in itemchild:
ic.text = listctrldata[j][k]
k+=1
j+=1
f = open(xml_file,"w")
f.write(etree.tostring(root,pretty-print = true))
f.close()