[ZT]Python使用xml.etree.ElementTree操作xml檔案__Python

來源:互聯網
上載者:User

http://blog.chinaunix.net/uid-11131943-id-2906278.html

一、基本知識
1、插入節點
Element.insert(index, element) 、ET.SubElement(parent, tag[, attrib[, **extra]]) 、Element.append(subelement)
2、刪除節點
Element.remove(subelement) 刪除一個節點、Element.clear()刪除該節點下所有子節點
3、在節點中插入屬性
Element.set(key, value)
  二、樣本  

# -*- coding:UTF-8 -*-

import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom

#擷取根節點
def getRoot(xmlpath):
    '''
    xmlpath:xml檔案的路徑
    '''
    root = ET.parse(xmlpath).getroot()
    return root

#格式化輸出xml檔案
def display(root):
    
    rough_string = ET.tostring(root, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    print reparsed.toprettyxml(indent=" " , encoding="utf-8");


if __name__ == '__main__':
    
    root = ET.Element('bookList')
    
    #==============添加節點========================
    #向root節點下插入節點<book id='ISO001'>
    bookE = ET.SubElement(root,'book')#方式一
    bookE.set('id', 'ISO001')#為節點添加屬性
    #向<book>節點下插入<author>Gaosilin</version>節點
    authorE = ET.Element('author')
    authorE.text = 'Gaosilin'#為節點賦值
    bookE.append(authorE)#方式二
    ##向<book>節點下插入<name>Java</name>節點
    nameE = ET.Element('name')
    nameE.text = 'java'
    bookE.insert(1,nameE)#方式三
    #修改
    nameE.text = '修改後的C'
    display(root)
    #==============刪除節點========================
    bookE.remove(nameE)#注意需刪除的節點一定要是該父節點的下一級節點
    bookE.remove(authorE)
    bookE.clear()#刪除該節點下的所有子節點,等價於上兩句
    root.remove(bookE)
# root.remove(nameE)#出錯:因為nameE的上一級節點是bookE而不是root
    display(root)

相關文章

聯繫我們

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