python中xml模块

1 xml定义

xml是实现不同语言或程序之间进行数据交换的协议,<>节点来区别数据结构。

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

3 遍历

 1 import xml.etree.ElementTree as ET
 2 
 3 tree = ET.parse("xlm_test")
 4 root = tree.getroot()
 5 print(root.tag)
 6 
 7 # 遍历xml文档
 8 for child in root:
 9     print(child.tag, child.attrib)  # 输出的是标签名字和字典类型的属性
10     for i in child:
11         print(i.tag)

4 修改

import xml.etree.ElementTree as ET

tree = ET.parse("xlm_test")
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('xlm_test2')

5 删除

import xml.etree.ElementTree as ET

tree = ET.parse("xlm_test")
root = tree.getroot()

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

tree.write('output.xml')

6 思路来源 

http://www.cnblogs.com/Acekr/p/7465239.html

http://www.cnblogs.com/godseven/articles/7349242.html

 

posted on 2018-04-22 10:41  Artisan正传  阅读(90)  评论(0)    收藏  举报