<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
# print(root.iter('year')) #全文搜索
# print(root.find('country')) #在root的子节点找,只找一个
# print(root.findall('country')) #在root的子节点找,找所有
import xml.etree.cElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()
'''三种查找节点的方式'''
'''=======================================查'''
# res=root.iter('rank') #会在整个树中进行查找,而且是查找到所有
# for item in res:
# print(item)
# print('='*50)
# print(item.tag) #标签名
# print(item.attrib) #属性
# print(item.text) #文本内容
#
#
# res=root.find('country') #只能在当前元素下一级开始查找,并且只找到一个就解释
# print(res.tag)
# print(res.attrib)
# print(res.text)
#
# nh=res.find('neighbor')
# print(nh.attrib)
#
# cy=root.findall('country') #只能在当前元素下一级开始查找
# print([item.attrib for item in cy])
'''=======================================改'''
# 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')
'''=======================================增加'''
for country in root.iter('country'):
# print(country)
year=country.find('year')
if int(year.text)>2020:
print(country.attrib)
ele=ET.Element('egon')
ele.attrib={'nb':'yes'}
ele.text='非常帅'
country.append(ele)
tree.write('b.xml')
'''=======================================删除'''
# for country in root.iter('country'):
# # print(country)
# year=country.find('year')
# if int(year.text) > 2020:
# # print(country.attrib)
# # ele=ET.Element('egon')
# # ele.attrib={'nb':'yes'}
# # ele.text='非常帅'
# # country.append(ele)
# country.remove(year)
# tree.write('b.xml')