python总结——处理XML(xml.etree.ElementTree)

2016-05-03  橙子 

python处理XML

我们使用下面的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>

 

1、导入ElementTree

在使用xml.etree.ElementTree时,一般都按如下导入:

try:

    import xml.etree.cElementTree as ET

except ImportError:

    import xml.etree.ElementTree as ET

 

2、导入数据

  1. #从硬盘的xml文件读取数据
  1. tree = ET.parse('E:/country_data.xml')
  1. #从字符串读取数据
  1. root = ET.fromstring(country_data_as_string)

 

3、读取数据

Element.iter(tag):遍历该Element所有后代,也可以指定tag进行遍历寻找。

Element.findall(tag/path):查找当前元素下tag或path能够匹配的直系节点。

Element.find(tag/path):查找当前元素下tag或path能够匹配的首个直系节点。

Element.text: 获取当前元素的text值。

Element.get(key):获取元素指定key对应的属性值,如果没有该属性,则返回default值。

Element.iter(tag)

  1. >>> for neighbor in root.iter('neighbor'):
  1. ...   print neighbor.attrib
  1. ...
  1. {'name': 'Austria', 'direction': 'E'}
  1. {'name': 'Switzerland', 'direction': 'W'}
  1. {'name': 'Malaysia', 'direction': 'N'}
  1. {'name': 'Costa Rica', 'direction': 'W'}
  1. {'name': 'Colombia', 'direction': 'E'}

findall,find,get

  1. >>> for country in root.findall('country'):
  1. ...   rank = country.find('rank').text
  1. ...   name = country.get('name')
  1. ...   print name, rank
  1. ...
  1. Liechtenstein 1
  1. Singapore 4
  1. Panama 68

 

4、修改xml文件

Element.text=new_value  修改节点值为new_value

ElementTree.write(path) 保存修改后的文件

 

write(file, encoding="utf-8")

file:文件名,或者打开进行写操作的文件对象

encoding:结果文件的编码格式,默认是US-ASCII,可以改为’utf=8’

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

 

766°/7661 人阅读/0 条评论 发表评论

登录 后发表评论