Python--xml Module

Source: Internet
Author: User

#==========================================> Search
Import Xml.etree.ElementTree as ET #导包, renaming
# tree=et.parse (' A.xml ') #将a. xml file parsed into a tree
# root=tree.getroot () #得到根节点


#三种查找节点的方式
# res=root.iter (' rank ') # ITER will look through the tree and find all
# for item in Res:
# # Print (item)
# print (' = ' *50)
# print (item.tag) # label Signature
# print (Item.attrib) #属性
# print (Item.text) #文本内容


# res=root.find (' country ') # find can only start at the next level of the current element. And just find one and end it.
# Print (Res.tag)
# Print (Res.attrib)
# Print (Res.text)
# nh=res.find (' neighbor ')
# Print (Nh.attrib)


# Cy=root.findall (' Country ') # FindAll can only start looking at the next level of the current element, but will find all
# print ([Item.attrib for item in CY])

Several operations of the XML file: change, increase, delete

#==========================================> Change
# import Xml.etree.ElementTree as ET
# tree=et.parse (' A.xml ')
# Root=tree.getroot ()
#
# for year in Root.iter (' year '):
# year.text=str (int (year.text) + 10)
# year.attrib={' Updated ': ' Yes '}
#
# # Tree.write (' B.xml ') #写到另一个文件里
# tree.write (' A.xml ')

#==========================================> Increase
Import Xml.etree.ElementTree as ET
Tree=et.parse (' A.xml ')
Root=tree.getroot ()

For country in Root.iter (' Country '):
# Print (country)
Year=country.find (' year ')
# Print (year)
if int (year.text) > 2020:
# Print (Country.attrib)
# Ele=et. Element (' Mr.haigui ') #设定标签
# ele.attrib={' nb ': ' Yes ' #设定属性
# ele.text= ' very handsome ' #设定文本内容
# country.append (ele) #增加操作
Country.remove (year) #删除操作
Tree.write (' B.xml ')

Python--xml Module

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.