ElementTree是Python常用的处理XML文件的类。下面将介绍使用ElementTree解析、查找、修改XML的方法。
1、引用方法
import xml.etree.ElementTree as ET
2、一个XML例子
下面所有的操作都将下面这段XML为例,我们将它保存为sample.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>
先对XML的格式做一些说明:
Tag: 标签,如country标签
Element:被Tag包围的部分,值,如 68,2011 等
Attribute:标签的属性,如country标签的name
3、解析XML
3.1 读取
读入XML数据有三种途径,从文件读入和从字符串读入,文件读入有2种
1、python3.3之后ElementTree模块会自动寻找可用的C库来加快速度
import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
2、调用ElementTree类ElementTree(self, element=None, file=None) # 这里的element作为根节点
import xml.etree.ElementTree as ET
tree = ET.ElementTree(file="country.xml")
root = tree.getroot() # <Element 'data' at 0x030EA600>
3、从字符串读入:
import xml.etree.ElementTree as ET
data = open("country.xml").read()
root = ET.fromstring(data)
# root = ET.fromstring(sample_as_string)
3.2 查看Tag和Attribute
# 当要获取属性值时,用attrib方法。 返回一个字典,如
print(root.attrib)
# 可以Element.get(AttributeName)来代替Element.attrib[AttributeName]来访问。
# 当要获取节点值时,用text方法。返回一个字符串,如
print(root.text)
# 当要获取节点名时,用tag方法。 返回一个字符串,如
print(root.tag)
3.3 查看孩子
.root.attrib返回的是一个空字典,如果看root的孩子,可以得到非空的attrib字典。
1、使用for...in...查询根节点下二级节点的所有元素
print(root.tag)# 根节点标签
for child in root:
print(child.tag,child.attrib) # 二级节点标签、属性、内容,结果得到
# country {'name': 'Liechtenstein'}
# country {'name': 'Singapore'}
# country {'name': 'Panama'}
2、使用findall等查询根节点下的元素
Element.iter()用来寻找所有符合要求的Tag,注意,这里查找的范围是所有孩子和孩子的孩子 and so
Element.findall()只查找直接的孩子,返回所有符合要求的Tag的Element
Element.find()只返回符合要求的第一个Element。如果查看Singapore的year的值
for child in root.findall('.//country'):
print(child.tag,child.attrib)
4、修改XML
前面已经介绍了如何获取一个Element的对象,以及查看它的Tag、Attribute、值和它的孩子。下面介绍如何修改一个Element并对XML文件进行保存
修改Element。修改Element可以直接访问Element.text。
import xml.etree.ElementTree as ET
# 修改Element的Attribute,也可以用来新增Attribute:
ET.Element.set('AttributeName','AttributeValue')
# 新增孩子节点:
root.append(childElement)
# 删除孩子节点:
root.remove(childElement)
保存XML。我们从文件解析的时候,我们用了一个ElementTree的对象tree,在完成修改之后,还用tree来保存XML文件。
tree.write('output.xml')
构建XML。ElementTree提供了两个静态函数(直接用类名访问,这里我们用的是ET)可以很方便的构建一个XML,如:
import xml.etree.ElementTree as ET
root = ET.Element('data')
country = ET.SubElement(root,'country', {'name':'Liechtenstein'}) # root 增加 country 节点
rank = ET.SubElement(country,'rank') # country 增加 rank 节点
rank.text = '1'
year = ET.SubElement(country,'year') # country 增加 year节点
year.text = '2008'
ET.dump(root)
5、XPath支持
XPath表达式用来在XML中定位Element,下面给一个例子来说明:
import xml.etree.ElementTree as ET
root = ET.fromstring(countrydata)
# Top-level elements
root.findall(".")
# All 'neighbor' grand-children of 'country' children of the top-level
# elements
root.findall("./country/neighbor")
# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@name='Singapore']")
# 'year' nodes that are children of nodes with name='Singapore'
root.findall(".//*[@name='Singapore']/year")
# All 'neighbor' nodes that are the second child of their parent
root.findall(".//neighbor[2]")
6、namespace
6.1 namespace 获取
# namespace 为 正则匹配获取,可能不同版本的会获取不到
root = tree.getroot()
namespace = re.search('\{.*?\}', root.tag)[0]
6.2 xml.etree.Element 在处理含有namespace的xml文件时写入会产生ns0
root = tree.getroot()
namespace = re.search('\{.*?\}', root.tag)[0]
ET.register_namespace('', namespace.strip('{}')) # 部分人说这步需要在parse之前做,在我的版本上不需要
7、其他错误
7.1 Error parsing XML: junk after document element
一般合法的XML文件只有一个主根节点,比如
<android123>
<item1/>
<item2/>
<item3/>
</android123>
如果出现了Error parsing XML: junk after document element这样的错误,你的想法可能只要主根有多个节点,比如说
<android123>
<item1/>
</android123>
<android123>
<item2/>
<item3/>
</android123>
xml不能解析,原因有可能为xml格式写的不对,考虑根节点不对。