1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python:xml模块用法-xml处理 修改 删除

python:xml模块用法-xml处理 修改 删除

时间:2020-08-23 21:47:54

相关推荐

python:xml模块用法-xml处理 修改 删除

xmltest.xml内容如下:

<data>

<country name="Liechten">

<rank updated="yes">1</rank>

<year updated_by="Alex"></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) #打印生成的格式

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。