ElementTree處理xml

來源:互聯網
上載者:User
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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.