Python對XML檔案的讀寫案例分享

來源:互聯網
上載者:User
這篇文章主要介紹了詳解 Python 讀寫XML檔案的執行個體的相關資料,Python 產生XML檔案和Python 讀取XML 的執行個體,需要的朋友可以參考下

詳解 Python 讀寫XML檔案的執行個體

Python 產生XML檔案


from xml.dom import minidom# 產生XML檔案方式def generateXml():  impl = minidom.getDOMImplementation()  # 建立一個xml dom  # 三個參數分別對應為 :namespaceURI, qualifiedName, doctype  doc = impl.createDocument(None, None, None)  # 建立根項目  rootElement = doc.createElement('Pythons')  # 為根項目添加10個子項目  for pythonId in range(10):    # 建立子項目    childElement = doc.createElement('python')    # 為子項目添加id屬性    childElement.setAttribute('id', str(pythonId))    # 將子項目追加到根項目中    rootElement.appendChild(childElement)    print(childElement.firstChild.data)  # 將拼接好的根項目追加到dom對象    doc.appendChild(rootElement)  # 開啟test.xml檔案 準備寫入  f = open('test.xml', 'a')  # 寫入檔案  doc.writexml(f, addindent=' ', newl='\n')  # 關閉  f.close()# 執行產生xml方法generateXml()

python 讀取XML檔案


from xml.dom.minidom import parse# 擷取 python節點下得所有id屬性def getTagId():  # 擷取test.xml文檔對象  doc = parse("test.xml")  for node in doc.getElementsByTagName("python"):    # 擷取標籤ID屬性    value_str = node.getAttribute("id")    # 列印輸出    print(value_str)# 擷取屬性IDgetTagId()

運行結果 – 產生xml檔案如下

運行結果 – 讀取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.