python解析xml檔案執行個體分析
本文執行個體講述了python解析xml檔案的方法。分享給大家供大家參考。具體如下:
python解析xml非常方便。在dive into python中也有講解。
如果xml的結構如下:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>
<author>zoer</author>
<title>think in java</title>
<content>this is a good book</content>
</book>
<book>
<author>naughty</author>
<title>gone with the wind</title>
<content>this is a good book 2</content>
</book>
<book>
<author>cc</author>
<content>this is a good book 3</content>
</book>
</books>
|
第三個book是沒有title標記的。由於不要相信代碼輸入,所以在代碼中要做檢查(比如說檢查這裡的有沒有子標籤)。
解析代碼如下:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 |
#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程式設計有所協助。