你好,我要是想通过python的ElementTree的XML接口实现xml的删除,修改,创建的功能该怎么编写。麻烦了。 55
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()
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()
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询