#==========================================> 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