python解析xml文件實例分析
更新時間:2015年05月27日 09:41:30 作者:imzoer
這篇文章主要介紹了python解析xml文件的方法,實例分析了Python針對XML文件節(jié)點及字段的獲取技巧,非常簡單實用,需要的朋友可以參考下
本文實例講述了python解析xml文件的方法。分享給大家供大家參考。具體如下:
python解析xml非常方便。在dive into python中也有講解。
如果xml的結(jié)構(gòu)如下:
<?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標(biāo)記的。由于不要相信代碼輸入,所以在代碼中要做檢查(比如說檢查這里的有沒有子標(biāo)簽)。
解析代碼如下:
#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
#獲取每一個下一層節(jié)點
for node in root.childNodes:
#這樣取得的是root節(jié)點以下一層的節(jié)點,而不是root節(jié)點以下所有節(jié)點
#取所有非text節(jié)點
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程序設(shè)計有所幫助。
相關(guān)文章
python openpyxl提取Excel圖片實現(xiàn)原理技巧
在這篇文章中,將介紹如何使用openpyxl來提取Excel中的圖片,以及它的原理和技巧,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01

