Xmltest.xml content is as follows:
<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 processing:
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 the 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 module Usage-xml processing, modifying, deleting