python處理xml檔案

來源:互聯網
上載者:User

標籤:blog   work   dal   tag   第一個   workspace   節點   元素   color   

參考:https://docs.python.org/2/library/xml.etree.elementtree.html

例子:

<?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>

1、解析xml檔案

>>> os.getcwd()‘D:\\workspace\\testpython‘>>> import xml.etree.ElementTree as ET>>> tree = ET.parse(‘test.xml‘)>>> root = tree.getroot()>>> print root<Element ‘data‘ at 0x1d2a8b0>>>> print tree<xml.etree.ElementTree.ElementTree object at 0x01D2A9D0>>>> root.tag‘data‘>>> root.attrib{}>>> #遍曆子節點>>> for child in root:    print child.tag,child.attrib    country {‘name‘: ‘Liechtenstein‘}country {‘name‘: ‘Singapore‘}country {‘name‘: ‘Panama‘}>>> root[0].text‘\n        ‘>>> root[0][1].text‘2008‘>>> root[1][3].text>>> root[1][2].text‘59900‘

2、尋找元素

>>> #查詢元素>>> for neighbor in root.iter(‘neighbor‘):    print neighbor.attrib    {‘direction‘: ‘E‘, ‘name‘: ‘Austria‘}{‘direction‘: ‘W‘, ‘name‘: ‘Switzerland‘}{‘direction‘: ‘N‘, ‘name‘: ‘Malaysia‘}{‘direction‘: ‘W‘, ‘name‘: ‘Costa Rica‘}{‘direction‘: ‘E‘, ‘name‘: ‘Colombia‘}>>> root.iter(‘neighbor‘)<generator object iter at 0x01D3CF30>>>> root.findall(‘country‘)[<Element ‘country‘ at 0x1d2aa90>, <Element ‘country‘ at 0x1d2ad30>, <Element ‘country‘ at 0x1d2af10>]>>> for country in root.findall(‘country‘): #element.findall()查詢當前元素的子項目    rank=country.find(‘rank‘).text  #element.find()查詢指定標籤的第一個子項目,element.text擷取元素的內容    name=country.get(‘name‘)  #element.get()擷取元素的屬性值    print name,rank    Liechtenstein 1Singapore 4Panama 68

3、修改xml檔案

 

python處理xml檔案

聯繫我們

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