模块:xml

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>
xml_test

xml操作

import xml.etree.ElementTree as ET

tree = ET.parse("xml_test.xml")
root = tree.getroot()

print(root.tag)

# 遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag, i.text,i.attrib)

# 只遍历year 节点
for node in root.iter('year'):
    print(node.tag, node.text)

 修改和删除xml

import xml.etree.ElementTree as ET

tree = ET.parse("xml_test.xml")
root = tree.getroot()

# 修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated", "yes")

tree.write("xml_test.xml")

# 删除node
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)

tree.write('output.xml')

 创建xml

import xml.etree.ElementTree as ET

new_xml = ET.Element("person_infolist")
person_info = ET.SubElement(new_xml, "person_info", attrib={"enrolled": "yes"})
name = ET.SubElement(person_info, "name")
age = ET.SubElement(person_info, "age", attrib={"checked": "no"})
sex = ET.SubElement(person_info, "sex")
name.text = 'q1ang'
age.text = '26'
person_info2 = ET.SubElement(new_xml, "person_info", attrib={"enrolled": "no"})
name = ET.SubElement(person_info2, "name")
age = ET.SubElement(person_info2, "age")
name.text='q2nag'
age.text = '25'

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

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

>>>

<?xml version='1.0' encoding='utf-8'?>
<person_infolist>
    <person_info enrolled="yes">
        <name>q1ang</name>
        <age checked="no">26</age>
        <sex />
    </person_info>
    <person_info enrolled="no">
        <name>q2nag</name>
        <age>25</age>
    </person_info>
</person_infolist>
test.xml

 

 

 

 

posted @ 2018-05-09 23:22  q1ang  阅读(148)  评论(0编辑  收藏  举报