python操作XML__python

來源:互聯網
上載者:User

XML是實現不同語言或程式之間進行資料交換的協議,XML檔案格式如下:

<data>    <country name="Liechtenstein">        <rank updated="yes">2</rank>        <year age="25">2033</year>        <gdppc>141100</gdppc>        <neighbor direction="E" name="Austria" />        <neighbor direction="W" name="Switzerland" />    </country>    <country name="Singapore">        <rank updated="yes">5</rank>        <year age="25">2036</year>        <gdppc>59900</gdppc>        <neighbor direction="N" name="Malaysia" />    </country>    <country name="Panama">        <rank updated="yes">69</rank>        <year age="25" type="date">2036</year>        <gdppc>13600</gdppc>        <neighbor direction="W" name="Costa Rica" />        <neighbor direction="E" name="Colombia" />    </country></data>
我們建立操作XMl對象有2種建立方法 如下

# -*- coding: utf-8 -*-from xml.etree import  ElementTree as ET#開啟檔案 讀取XML內容   第一種建立方法str_xml= open('data.xml','r').read()#將字串解析成xml特殊對象,root代指xml檔案的根節點root = ET.XML(str_xml)  #dataprint(root)   #返回一個對象#輸出 <Element 'data' at 0x1006feb50># 第二種建立方法# 直接解析xml檔案tree = ET.parse('data.xml')#擷取xml檔案的根節點root = tree.getroot()print(root) #輸出 <Element 'data' at 0x101821650>
我們可以查看data.xml所有的節點

#便利所有的子節點for child in root:    #第二層    print(child.tag,child.attrib)  #輸出一個元組    #對第二層節點下面的子節點進行便利    for i in child:        print(i.tag,i.attrib)

擷取指定的節點
#擷取xml中的制定節點for child in root.iter('year'):    print(child.tag,child.attrib)

對XML中的操作一般是在記憶體中進行的,不會影響到檔案中的內容,因此我們在記憶體中寫完之後需要重新寫入檔案

#對xml檔案進行操作 增刪改查for node in root.iter('year'):    # 將year內容+10    new_year = int(node.text)+10    node.text = str(new_year)    # 設定屬性    node.set('name','eric')    node.set('age','25')    #刪除屬性    del node.attrib['age']#儲存到檔案tree = ET.ElementTree(root)tree.write('data.xml',encoding='utf-8')#刪除節點for country in root.findall('country'):   # 擷取每一個country節點下rank節點的內容   rank =  int(country.find('rank').text)   if rank > 50:       root.remove(country)  #會刪除掉  整個country節點和下面的內容#儲存到檔案tree = ET.ElementTree(root)tree.write('data.xml',encoding='utf-8')



聯繫我們

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