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、导入数据
- #从硬盘的xml文件读取数据
- tree = ET.parse('E:/country_data.xml')
- #从字符串读取数据
- 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)
- >>> 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'}
findall,find,get
- >>> for country in root.findall('country'):
- ... rank = country.find('rank').text
- ... name = country.get('name')
- ... print name, rank
- ...
- Liechtenstein 1
- Singapore 4
- Panama 68
4、修改xml文件
Element.text=new_value 修改节点值为new_value
ElementTree.write(path) 保存修改后的文件
write(file, encoding="utf-8")
file:文件名,或者打开进行写操作的文件对象
encoding:结果文件的编码格式,默认是US-ASCII,可以改为’utf=8’
- >>> 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')