ElementTree是Python常用的處理XML文件的類。下面將介紹使用ElementTree解析、查找、修改XML的方法。
一、引用方法
import xml.etree.ElementTree as ET
二、一個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
三、解析XML
讀入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)
查看Tag和Attribute
# 當要獲取屬性值時,用attrib方法。 返回一個字典,如
print(root.attrib[])
# 當要獲取節點值時,用text方法。返回一個字符串,如
print(root.text)
# 當要獲取節點名時,用tag方法。 返回一個字符串,ru
print(root.tag)
Element.get(AttributeName)來代替Element.attrib[AttributeName]來訪問。
查看孩子.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)
四、修改XML
前面已經介紹瞭如何獲取一個Element的對象,以及查看它的Tag、Attribute、值和它的孩子。下面介紹如何修改一個Element並對XML文件進行保存
修改Element。修改Element可以直接訪問Element.text。
# 修改Element的Attribute,也可以用來新增Attribute:
Element.set('AttributeName','AttributeValue')
# 新增孩子節點:
Element.append(childElement)
# 刪除孩子節點:
Element.remove(childElement)
保存XML。我們從文件解析的時候,我們用了一個ElementTree的對象tree,在完成修改之後,還用tree來保存XML文件。
tree.write('output.xml')
構建XML。ElementTree提供了兩個靜態函數(直接用類名訪問,這裏我們用的是ET)可以很方便的構建一個XML,如:
root = ET.Element('data')
country = ET.SubElement(root,'country', {'name':'Liechtenstein'})
rank = ET.SubElement(country,'rank')
rank.text = '1'
year = ET.SubElement(country,'year')
year.text = '2008'
ET.dump(root)
五、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]")