python:xml模块用法-xml处理修改删除
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python:xml模块用法-xml处理修改删除相关的知识,希望对你有一定的参考价值。
xmltest.xml内容如下:
<data>
<country name="Liechten">
<rank updated="yes">1</rank>
<year updated_by="Alex">2017</year>
<gdppc>140000</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
</data>
xml处理:
import xml.tree.ElementTree as ET
tree=ET.parse("xmltest.xml")
root=tree.getroot() #获取根节点
print(root)
print(root.tag)
#遍历xml
for child in root:
......print(child.tag,child.attrib) #打印孩子节点标签和属性
......for i in child:
............print(i.tag,i.text.i.attrib)
#只遍历year节点
for node in root.iter(‘year‘)
......print(node.tag,node.text)
#xml修改
for node in root.iter(‘year‘):
......new_year=int(node.text)
......node.text=str(new_year)
......node.set("updated_by","cai")
tree.write("xmltest.xml")
#删除
for country in root.findall(‘country‘):
......rank=int(country.find(‘rank‘).text)
......if rank>50:
..........root.remove(country)
tree.write(‘output.xml‘)
#自己编写
import xml.etree.ElementTree as ET
new_xml=ET.Element("personinfolist")
personinfo=ET.SubElement(new_xml,"personinfo",attrib={"enrolled":"yes"})
name=ET.SubElement(personinfo,"name")
name.text="huaha"
age=ET.SubElement(personinfo,"age",attrib={"checked":"no"})
age.text=‘12‘
et=ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml",encoding=‘utf-8‘,xml_declaration=True)
ET.dump(new_xml) #打印生成的格式
以上是关于python:xml模块用法-xml处理修改删除的主要内容,如果未能解决你的问题,请参考以下文章