#增删改查#在进行操作之前,都应该进行这两步:
#import xml.etree.ElementTree as ET#tree = ET.parse('a.xml') # 形成树形结构#root = tree.getroot() # 得到树的根系#print(root)#循环打印:#for i in root:#print(i)###
#所有的增删改查都是基于这个root根系去操作
#查:#1,全文搜索 year 将所有的year标签全部找#print(root.iter('year'))#print([i for i in root.iter('year')])#2,只找第一个,找到就返回#print(root.find('country'))#3,在root的子节点找,找所有的#print(root.findall('country'))
#练习#找到标签也可以找到标签相应的内容:tag,attrib,text
#1,找所有的rank标签,以及 attrib 和 text (这里利用列表推导式比较方便)#print([i for i in root.iter('rank')])#[, , ]#print([i.attrib for i in root.iter('rank')])#[{'updated': 'yes'}, {'updated': 'yes'}, {'updated': 'yes'}]#print([i.text for i in root.iter('rank')]) # ['2', '5', '69']
#2,找到第二个country的 neighbor标签以及他的属性#print([tag for tag in root.findall('country')][1].find('neighbor').attrib)#{'direction': 'N', 'name': 'Malaysia'}
#增 append#import xml.etree.ElementTree as ET#tree = ET.parse('a.xml') # 形成树形结构#root = tree.getroot() # 得到树的根系
#给 year 大于2010年的所有标签下面添加一个month标签,属性为name:month 内容为30days
#for country in root.findall('country'):#for year in country.findall('year'):#if int(year.text) > 2010:#month = ET.Element('month')#month.text = '30days'#month.attrib = {'name': 'month'}#country.append(month)#tree.write('b.xml')
#改
#import xml.etree.ElementTree as ET#tree = ET.parse('a.xml') # 形成树形结构#root = tree.getroot() # 得到树的根系#对所有的year属性以及值进行修改#for node in root.iter('year'):#new_year=int(node.text)+1#node.text=str(new_year)#node.set('updated','yes')#node.set('version','1.0')#tree.write('test.xml')
#删#import xml.etree.ElementTree as ET#tree = ET.parse('a.xml') # 形成树形结构#root = tree.getroot() # 得到树的根系#
## 将 rank值大于50的country标签删除#for country in root.findall('country'):#rank = int(country.find('rank').text)#if rank > 50:#root.remove(country)#
#tree.write('output.xml')