您好,登录后才能下订单哦!
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) #打印生成的格式
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。