xml模块

 1 import xml.etree.ElementTree as ET
 2 
 3 tree = ET.parse('xmltest.xml')
 4 root = tree.getroot()  # 一个对象
 5 print(root.tag)  # 打印标签名
 6 for country in root.findall('country'):  # 寻找所有的节点
 7     rank = int(country.find('rank').text)  # 寻找一个节点
 8     if rank>50:
 9         root.remove(country)   # 一处一个节点
10 tree.write('abc.xml')
11 for i in root.iter('year'):  #指定某个标签的属性
12     print(i.attrib)
13     # print(i.tag)
14 for n in i:
15     print(n.tag)
16 print(i.attrib)  # 打印属性
17 for n in i:
18     # print(n.attrib)
19     print(n.text)  # 打印标签的文本
20 for i in root.iter('year'):
21     new_str = int(i.text) + 10000  # 提取原文本值
22     i.text = str(new_str)  # 修改文本属性
23     i.set('name', '大幅度顺丰到付') # 设置属性
24 tree.write('')
25 new_xml = ET.Element('namelist')
26 name = ET.SubElement(new_xml, 'name', attrib={'enrolled': 'yes'})
27 age = ET.SubElement(name, 'age', attrib={'age': '167'})
28 info = ET.SubElement(name, 'info', attrib={'info': 'weihun'})
29 name.text = 'liyulu'
30 age.text = '15'
31 info.text = 'weizhi'
32 name2 = ET.SubElement(new_xml,'name2',attrib={'name':'nihao'})
33 age = ET.SubElement(name2,'age',attrib={'age':'88'})
34 age.text = '99'
35 et = ET.ElementTree(new_xml)
36 et.write('test.xml', encoding='utf-8', xml_declaration=True)

总结:使用et.parse()  进行解析    在调用对象的getroot()方法进行取节点     findall() 取所有节点   find() 取一个节点     attrib  取属性       tag取节点名

使用text取值并可以进行修改赋值      修改和新建最后要进行保存

原文地址:https://www.cnblogs.com/ch2020/p/12403846.html