python xml解析之 xml.etree.ElementTree

來源:互聯網
上載者:User

標籤:print   XML   country   sub   1.0   parse   ppc   body   解析   

import xml.etree.ElementTree as treeimport ioxml = ‘‘‘<?xml version="1.0"?><data>    <country name="Liechtenstein">        <rank updated="yes">2</rank>        <year>2008</year>        <gdppc>141100</gdppc>        <neighbor name="Austria" direction="E"/>        <neighbor name="Switzerland" direction="W"/>    </country>    <country name="Singapore">        <rank updated="yes">5</rank>        <year>2011</year>        <gdppc>59900</gdppc>        <neighbor name="Malaysia" direction="N"/>    </country>    <country name="Panama">        <rank updated="yes">69</rank>        <year>2011</year>        <gdppc>13600</gdppc>        <neighbor name="Costa Rica" direction="W"/>        <neighbor name="Colombia" direction="E"/>    </country></data>‘‘‘parse = tree.fromstring(xml) #type:tree.Element #根節點for e in parse: #遍曆    print(e.tag) # 節點名稱    print(e.attrib.get(‘name‘))#節點屬性result = parse.findall(‘country‘) # 只能找到子節點 第一層print(result) #[<Element ‘country‘ at 0x0000000001DDE7C8>, <Element ‘country‘ at 0x000000000291F908>, <Element ‘country‘ at 0x000000000291FA98>]print([e for e in parse.iter(‘rank‘) if e.attrib.get(‘updated‘) == ‘yes‘]) #遞迴遍曆所有#父節點 parse 添加子節點print(tree.SubElement(parse, ‘test‘, attrib={‘name‘: ‘ceshi‘})) #工廠方式添加子節點print(tree.tostring(parse).decode(‘utf-8‘)) #輸出xml文檔

 

python xml解析之 xml.etree.ElementTree

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.