1 # xml 处理
2 import xml.etree.ElementTree as ET
3
4 tree = ET.parse("xml_test.xml")
5 root = tree.getroot()
6 print(root.tag)
7
8 # 遍历xml文档
9 for child in root:
10 print(child.tag, child.attrib)
11 for i in child:
12 print(i.tag, i.text)
13
14 # 只遍历year 节点
15 for node in root.iter('year'):
16 print(node.tag, node.text)
17
18
19 ------------------------------------------------
20
21
22 # xml 修改
23 import xml.etree.ElementTree as ET
24
25 tree = ET.parse("xml_test.xml")
26 root = tree.getroot()
27
28 # 修改
29 for node in root.iter('year'):
30 new_year = int(node.text) + 1
31 node.text = str(new_year)
32 node.set("updated", "yes")
33
34 tree.write("xmltest.xml")
35
36 # 删除node
37 for country in root.findall('country'):
38 rank = int(country.find('rank').text)
39 if rank > 50:
40 root.remove(country)
41
42 tree.write('output.xml')
43
44
45 -----------------------------------------------------------
46
47
48 # xml 创建
49 import xml.etree.ElementTree as ET
50
51
52 new_xml = ET.Element("namelist")
53 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
54 age = ET.SubElement(name,"age",attrib={"checked":"no"})
55 sex = ET.SubElement(name,"sex")
56 sex.text = '33'
57 name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
58 age = ET.SubElement(name2,"age")
59 age.text = '19'
60
61 et = ET.ElementTree(new_xml) #生成文档对象
62 et.write("test.xml", encoding="utf-8",xml_declaration=True)
63
64 ET.dump(new_xml) #打印生成的格式
1 <data>
2 <country name="Liechtenstein">
3 <rank updated="yes">2</rank>
4 <year updated_by="Alex">2009</year>
5 <gdppc>141100</gdppc>
6 <neighbor direction="E" name="Austria" />
7 <neighbor direction="W" name="Switzerland" />
8 </country>
9 <country name="Singapore">
10 <rank updated="yes">5</rank>
11 <year updated_by="Alex">2012</year>
12 <gdppc>59900</gdppc>
13 <neighbor direction="N" name="Malaysia" />
14 </country>
15 <country name="Panama">
16 <rank updated="yes">69</rank>
17 <year updated_by="Alex">2012</year>
18 <gdppc>13600</gdppc>
19 <neighbor direction="W" name="Costa Rica" />
20 <neighbor direction="E" name="Colombia" />
21 <info>
22 <population>8</population>
23 <size>960</size>
24 </info>
25 </country>
26 </data>