Python xml处理模块

时间:2022-01-04 22:35:56

---恢复内容开始---

xml 通过< >节点来区别数据结构

 

---恢复内容结束---

xml 通过< >节点来区别数据结构

 

<xml version='1.0'>
<data>
    <country name="USA">
        <rank updated="yes">19</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name ="Austria"  direction="E"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">99</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name ="Switzerland" direction = "W"/>
    </country>
</data>

 

 1 # !/user/bin/python
 2 # -*- coding: utf-8 -*-
 3 
 4 import xml.etree.ElementTree as ET
 5 
 6 tree = ET.parse("xmltest.xml")
 7 root = tree.getroot()  # xml的内存地址
 8 print(root.tag)  # xml中的标签名
 9 
10 # 遍历xml文件
11 for child in root:
12     print(child.tag, child.attrib)
13     for i in child:
14         print(i.tag, i.text, i.attrib)
15 
16 
17 # 只遍历year节点
18 for node in root.iter('year'):
19     print(node.tag, node.text)
20 
21 
22 # 修改xml文档的内容
23 for node in root.iter('year'):
24     new_year = int(node.text)+1
25     node.text = str(new_year)
26     node.set("updated", "yes")  # 给year 添加属性updated, 值为yes
27     node.set("updated by", "Alex")  # 给year 添加属性updated by, 值为Alex
28 tree.write("xmltest.xml")
29 
30 
31 # 删除node
32 for country in root.findall("country"):
33     rank = int(country.fine('rank').text)
34     if rank > 30:  # rank的值大于30时,删掉相应的国家
35         root.remove('country')
36 tree.write("output.xml")

 

 

# !/user/bin/python
# -*- coding: utf-8 -*-

import xml.etree.ElementTree as ET

new_xml = ET.Element("personinfolist")
personinfo = ET.SubElement(new_xml, "personinfo", attrib={"enrolled":"yes"})
name = ET.SubElement(personinfo, "name")
name.text = "Alex"
age = ET.SubElement(personinfo, "age", attrib={"checked":"no"})
sex = ET.SubElement(personinfo, "sex")
age.text = "33"
personinfo2 = ET.SubElement(new_xml, "personinfo", attrib={"enrolled":"no"})
name = ET.SubElement(personinfo2, "name")
name.text = "Lucy"
age = ET.SubElement(personinfo2, "age")
age.text = "10"

et = ET.ElementTree(new_xml)  # 生成文件对象
et.write("text.xml", encoding='utf-8',xml_declaration=True)

ET.dump(new_xml)  # 打印生成的格式