1. 樣本用法 參照官方文檔,建立country_data.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>
使用如下代碼,將資料讀出,列印
from xml.etree.ElementTree data = ElementTree.ElementTree(file='country_data.xml')country_list = data.findall('country') #找到所有名為‘country’的tag,返回一個Element對象列表。for country in country_list: name = country.attrib.get('name', '') print name, ' ', for item in country: if item.tag == 'neighbor': name = item.attrib.get('name', '') direction = item.attrib.get('direction', '') print '{0} ({1})'.format(name, direction), ' ', else: print item.text, ' ', print ''
其中, data = ElementTree.ElementTree(file='country_data.xml')獲得一個ElementTree對象,也可以使用
tree = ElementTree.parse('country_data.xml')
Element對象具有如下屬性和操作
| elem.tag |
這個Element對象的名字(tag) |
| elem.text |
文檔內容 |
| elem.attrib |
屬性值字典 |
| elem.tail |
與屬性一起儲存的其他資料 |
elem[n] 返回elem的第n個子項目
elem[n] = new_elem 將elem的第n個子項目更改為不同的元素new_elem
del elem[n] 刪除子項目
len(elem) 子項目的數量
elem.find(path)
elem.getchildren() 按文檔順序返回所有子項目
elem.items()將所有元素的屬性值以(name, value)對列表形式返回 2.遇到非法格式的xml ExpatError: no element found
bad.xml為空白文檔時,內容如下:
<?xml version="1.0"?>
執行如下python代碼,遇到xml.parser.expat.ExpatError異常:
import xml.etree.ElementTree as ETET.parse('bad.xml')
xml.parsers.expat.ExpatError: no element found: line 3, column 0
ExpatError: mismatched tag
bad.xml中找不到對應結束標記符時,內容如下:
<?xml version="1.0"?><note></Note>
因為區分大小寫,所以</Note> 不能作為<note>的結束標記。
xml.parsers.expat.ExpatError: mismatched tag: line 3, column 2
ExpatError: not well-formed(invalid token)
bad.xml中屬性值未包含在雙引號(")之中時,遇到如下異常:
<?xml version="1.0"?><note id=hello></note>
bad.xml中非法符號,在"if salary < 1000 then"語句的‘<',如下:
<?xml version="1.0"?><note id="hello">if salary < 1000 then</note
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 2, column 9