python xml讀取和寫入

來源:互聯網
上載者:User
先說說如何建立一個XML檔案吧

# -*- coding: utf-8 -*-from xml.dom import minidomimpl = minidom.getDOMImplementation()dom = impl.createDocument(None, None, None)#namespaceURI, qualifiedName, doctype#write to domroot = dom.createElement("skills")for skillid in range(10):    skill= dom.createElement('skill')    skill.setAttribute('id', str(skillid))    root.appendChild( skill )dom.appendChild( root )#end write to dom#writexml(writer, indent, addindent, newl, encoding)#writer是檔案對象#indent是每個tag前填充的字元,如:'  ',則表示每個tag前有兩個空格#addindent是每個子結點的縮近字元#newl是每個tag後填充的字元,如:'\n',則表示每個tag後面有一個斷行符號#encoding是產生的XML資訊頭中的encoding屬性值,# 在輸出時minidom並不真正進行編碼的處理,如果你儲存的常值內容中有漢字,# 則需要自已進行編碼轉換。f=file('c:\\skills.xml','w')dom.writexml(f,'',' ','\n','utf-8')f.close()

這樣產生的XM了如下:

#######################

讀取XML

>>> dom = xml.dom.minidom.parse('c:/skills.xml')

>>> root = dom.documentElement

>>> root.nodeName

>>> r2.nodeName

u'skills'

  • 聯繫我們

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