python標準庫ElementTree處理xml
1. 示例用法
參照官方文檔,創(chuàng)建country_data.xml測試文檔,內(nèi)容如下:
<?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>使用如下代碼,將數(shù)據(jù)讀出,打印
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 | 文檔內(nèi)容 |
| elem.attrib | 屬性值字典 |
| elem.tail | 與屬性一起存儲的其他數(shù)據(jù) |
elem[n] 返回elem的第n個子元素
elem[n] = new_elem 將elem的第n個子元素更改為不同的元素new_elem
del elem[n] 刪除子元素
len(elem) 子元素的數(shù)量
elem.find(path)
elem.getchildren() 按文檔順序返回所有子元素
elem.items()將所有元素的屬性值以(name, value)對列表形式返回
遇到非法格式的xml
ExpatError: no element found
bad.xml為空文檔時,內(nèi)容如下:
<?xml version="1.0"?>
執(zhí)行如下python代碼,遇到xml.parser.expat.ExpatError異常:
import xml.etree.ElementTree as ET
ET.parse('bad.xml')xml.parsers.expat.ExpatError: no element found: line 3, column 0
ExpatError: mismatched tag
bad.xml中找不到對應(yīng)結(jié)束標記符時,內(nèi)容如下:
<?xml version="1.0"?> <note> </Note>
因為區(qū)分大小寫,所以</Note> 不能作為<note>的結(jié)束標記。
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
以上就是python標準庫ElementTree處理xml的詳細內(nèi)容,更多關(guān)于python ElementTree處理xml的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
keras的load_model實現(xiàn)加載含有參數(shù)的自定義模型
這篇文章主要介紹了keras的load_model實現(xiàn)加載含有參數(shù)的自定義模型,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python深度學習tensorflow實例數(shù)據(jù)下載與讀取
這篇文章主要為大家介紹了python深度學習tensorflow實例數(shù)據(jù)下載與讀取示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
Django靜態(tài)資源URL STATIC_ROOT的配置方法
這篇文章主要介紹了Django靜態(tài)資源URL STATIC_ROOT的配置方法,本文給出配置方法和兩種使用方法,需要的朋友可以參考下2014-11-11

