本文執行個體講述了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程式設計有所協助。