你好,我要是想通过python的ElementTree的XML接口实现xml的删除,修改,创建的功能该怎么编写。麻烦了。

2024-12-22 17:11:17
推荐回答(1个)
回答1:

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()