python解析xml示例

python是一种脚本语言,功能非常强大
我们来看看如何使用python来解析xml,举个粟子:
例1:解析xml
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>


import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
for child in root:
   print child.tag, child.attrib


结果:   
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'} 


作为一个元素来讲,root拥有标签和属性字典:
root.tag 就是'data'  
root.attrib 即为{}
遍历其孩子结点,即可以得到更里一层的标签和属性字典
for child in root:
   print child.tag, child.attrib
就能得到
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'} 
而child其实也是嵌套的,我们可以以二维数组的方式得到特定的元素:
root[0][1].text 即 2008


此处,你也可以只得到你感兴趣的元素:
例如:
for neighbor in root.iter('neighbor'):
   print neighbor.attrib


{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Malaysia', 'direction': 'N'}
{'name': 'Costa Rica', 'direction': 'W'}
{'name': 'Colombia', 'direction': 'E'}




例2:修改xml
for rank in root.iter('rank'):
   new_rank = int(rank.text) + 1
   rank.text = str(new_rank)
   rank.set('updated', 'yes')
tree.write('output.xml')


修改后的xml如下所示:rank部分被改变了
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>


例3,修改xml之2
我们可以通过Element.remove() 接口来删除xml文件中的元素
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
tree.write('output.xml')


得到结果如下:
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
</data>


例4,创建xml
SubElement()接口提供了一种创建子元素的简便的方法
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
ET.dump(a)


输出如<a><b /><c><d /></c></a>
构成如下:
<a>
<b />
<c>
<d />
</c>
</a>
   
例5,以命名空间的方式来解析xml
示例xml:(这个xml文件中添加了两个命名空间,其中一个的前缀是fictional,另外一个作为默认的命名空间)
<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
    </actor>
</actors>


方式一:在find()或者findall()接口中手动添加URI到每一个标签或者属性值前面。
root = fromstring(xml_text)
for actor in root.findall('{http://people.example.com}actor'):
    name = actor.find('{http://people.example.com}name')
    print name.text
    for char in actor.findall('{http://characters.example.com}character'):
        print ' |-->', char.text

方式二:在find()或者findall()接口中创建一个自己的前缀
ns = {'real_person': 'http://people.example.com',
      'role': 'http://characters.example.com'}


for actor in root.findall('real_person:actor', ns):
    name = actor.find('real_person:name', ns)
    print name.text
    for char in actor.findall('role:character', ns):
        print ' |-->', char.text

两者的输出均为:
John Cleese
 |--> Lancelot
 |--> Archie Leach
Eric Idle
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值