python初级之路-xml模块

python之xml模块:是早期实现不同语言或程序之间进行数据交换的协议模块,与json模块差不多。

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 
 4 import xml.etree.ElementTree as ET
 5 
 6 tree = ET.parse("xml_test.xml")    # 声明解析一个xml对象
 7 root = tree.getroot()    # 获取根节点
 8 print("根节点名称:", root.tag)
 9 
10 # 遍历整个 xml 文档
11 for child in root:
12     print("子节点名称:", child.tag, "子节点属性:", child.attrib)
13     # 遍历子节点的内容
14     for i in child:
15         print("--->", i.tag, i.text)
16 print("----------------------------------------------------")
17 
18 # 遍历 year 节点
19 for node in root.iter("year"):
20     print(node.tag, node.text)
21 
22 # 修改 year 节点数据
23 for node in root.iter("year"):
24     node_new = int(node.text) + 1    # 获取年份的值并+1
25     node.text = str(node_new)     # 将新生成的年份的值赋值给node.text
26     node.set("updated", "yes")    # 同时设置年份节点的属性值
27 
28 tree.write("xml_update.xml")     # 将新的xml对象写到xml_update.xml文档中
29 
30 # 删除一个 xml 节点
31 for country in root.findall("country"):    # 找到xml中所有的country节点
32     rank = int(country.find("rank").text)    # 找到country节点中所有的rank节点,并获取其值
33     if rank > 50:    # 将大于50的值所在的节点删除
34         root.remove(country)
35 
36 tree.write("xml_remove.xml")     # 将新的xml对象写到xml_remove.xml文档中
37 
38 # 创建一个新的xml对象文档
39 new_xml = ET.Element("namelist")    # 创建一个根节点
40 name = ET.SubElement(new_xml, "name", attrib={"enrolld": "yes"})    # 创建一个名为name的节点,并设置属性enrolld=yes
41 age = ET.SubElement(name, "age", attrib={"checked": "no"})    # 在name节点下创建一个age节点,并设置属性checked=no
42 sex = ET.SubElement(name, "sex")    # 在name节点下创建一个sex节点
43 
44 age.text = "33"    # 给age赋值为33
45 sex.text = "Male"    # 给sex赋值为Male
46 
47 name2 = ET.SubElement(new_xml, "name", attrib={"enrolld": "no"})
48 age = ET.SubElement(name2, "age")
49 sex = ET.SubElement(name2, "sex")
50 
51 age.text = "25"    # 给age赋值为25
52 sex.text = "Femal"    # 给sex赋值为Femal
53 
54 new_et = ET.ElementTree(new_xml)    # 生成一个xml文档对象
55 new_et.write("xml_new.xml", encoding="utf-8", xml_declaration=True)     # 将生成的xml对象写入到xml_new.xml文件中
56 
57 ET.dump(new_xml)    # 打印输出新xml对象

 

输出结果:

 

xml_test.xml文件:

 1 <?xml version="1.0"?>
 2 <data>
 3     <country name="Liechtenstein">
 4         <rank updated="yes">2</rank>
 5         <year>2008</year>
 6         <gdppc>141100</gdppc>
 7         <neighbor name="Austria" direction="E"/>
 8         <neighbor name="Switzerland" direction="W"/>
 9     </country>
10     <country name="Singapore">
11         <rank updated="yes">5</rank>
12         <year>2011</year>
13         <gdppc>59900</gdppc>
14         <neighbor name="Malaysia" direction="N"/>
15     </country>
16     <country name="Panama">
17         <rank updated="yes">69</rank>
18         <year>2011</year>
19         <gdppc>13600</gdppc>
20         <neighbor name="Costa Rica" direction="W"/>
21         <neighbor name="Colombia" direction="E"/>
22     </country>
23 </data>
posted @ 2020-10-19 20:44  Zombie☠️  阅读(118)  评论(0)    收藏  举报