参考地址:http://blog.csdn.net/yueguanghaidao/article/details/7265246
python的官方文档:https://docs.python.org/2/library/xml.etree.elementtree.html
前述,库文件说明:
Source code: Lib/xml/etree/ElementTree.py
导入的库文件为:from xml.etree import ElementTree
为了使用方便可以像命名别名方式:
from xml.etree import ElementTree as ET
理解:
element是个容器对象,有些属性:
1) 一个tag
2) 一些attrib,或者为空 {}
3) 一个text
4) 一些子element
它是介于list和dict的中间体容器。
find, findall 结果就是一个list( find和 findall的区别, find是查找第一tag对应的element下所有元素, findall是查找对应tag的所有elements)
root.attrib 结果就是一个dict
具体使用
下面是一个转载的例子:
test.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.加载xml文件
加载XML文件共有2种方法,一是加载指定字符串,二是加载指定文件
a) parse 加载xml文件
b) fromstring 加载指定字符串
2.获取element的方法
a) 通过getiterator
b) 过 getchildren
c) find方法
d) findall方法
通过例子学习下:
from xml.etree import ElementTree as ET
#coding=gbk
tree = ET.parse("test.xml")
root = tree.getroot()
print root.tag, root.attrib, root.text
for child in root:
print child.tag, child.attrib, root.text
#getiterator方法, 得到对应tag的所有elemnt的
countrys = root.getiterator("country")
for country in countrys:
print "===", country.tag, country.attrib
#得到root下的所有子元素
childs = root.getchildren()
for child in childs:
print "+++", child.tag, child.attrib
#find方法,查找对应tag的第一个elment下的elements,支持path
fchilds = root.find("country")
for fchild in fchilds:
print "---", fchild.tag, fchild.attrib
#findall方法,查找所有的对应tag的所有element, 支持path
fachilds = root.findall("country")
for fachild in fachilds:
print "---s", fachild.tag, fachild.attrib
fapchilds = root.findall("country/neighbor")
for fapchild in fapchilds:
print "---sp", fapchild.tag, fapchild.attrib
注意问题:
中文编码问题,ElementTree只支持 utf8编码
所以当时gbk编码的时候,需要转码。
字符串转码:str.decode('gbk').encode('utf8'), 并且xml的头文件encoding为gbk的需要修改,如:
<?xml version='1.0' encoding='GBK'?>
则需要str=str.replace('GBK', 'utf-8')