python解析xml檔案執行個體分析

來源:互聯網
上載者:User
本文執行個體講述了python解析xml檔案的方法。分享給大家供大家參考。具體如下:

python解析xml非常方便。在dive into python中也有講解。

如果xml的結構如下:

<?xml version="1.0" encoding="utf-8"?>         zoer     think in java     this is a good book           naughty     gone with the wind     this is a good book 2           cc     this is a good book 3    

第三個book是沒有title標記的。由於不要相信代碼輸入,所以在代碼中要做檢查(比如說檢查這裡的有沒有子標籤)。

解析代碼如下:

#coding=utf-8 #parse all books #author:  naughty610 #date:   2012-8-16 import xml.dom.minidom dom = xml.dom.minidom.parse('C:/Users/naughty/Desktop/books.xml') root = dom.documentElement #擷取每一個下一層節點 for node in root.childNodes:#這樣取得的是root節點以下一層的節點,而不是root節點以下所有節點   #取所有非text節點   if node.nodeType == node.ELEMENT_NODE:     #取author欄位     author=node.getElementsByTagName("author")     if len(author)>=1:       print author[0].childNodes[0].data     #取title欄位     title=node.getElementsByTagName("title")     if len(title)>=1:       print title[0].childNodes[0].data     #取content欄位     content=node.getElementsByTagName("content")     if len(content)>=1:       print content[0].childNodes[0].data     print "........................parting line........................"

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

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