国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python解析xml文件實例分析

2020-02-23 01:25:01
字體:
來源:轉載
供稿:網友

本文實例講述了python解析xml文件的方法。分享給大家供大家參考。具體如下:

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

如果xml的結構如下:

<?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標記的。由于不要相信代碼輸入,所以在代碼中要做檢查(比如說檢查這里的有沒有子標簽)。

解析代碼如下:

#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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 诸城市| 乌兰察布市| 旅游| 禹州市| 赤城县| 达州市| 齐河县| 安顺市| 尚义县| 伊宁县| 古交市| 东丰县| 太和县| 温州市| 东港市| 舟曲县| 石台县| 商洛市| 新沂市| 五峰| 郸城县| 竹北市| 新巴尔虎左旗| 准格尔旗| 华安县| 嘉定区| 北票市| 漳州市| 全椒县| 永安市| 澳门| 南乐县| 平乐县| 常宁市| 江油市| 玉环县| 济阳县| 郸城县| 铜川市| 商都县| 黄冈市|