Python:xml module Usage-xml processing, modifying, deleting

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.