html5中文学习网

您的位置: 首页 > 网站及特效实例 > jquery特效 » 正文

python解析xml文件实例分析_编程语言综合

[ ] 已经帮助:人解决问题

   本文实例讲述了python解析xml文件的方法。分享给大家供大家参考。具体如下:7TAHTML5中文学习网 - HTML5先行者学习网

  python解析xml非常方便。在dive into python中也有讲解。7TAHTML5中文学习网 - HTML5先行者学习网

  如果xml的结构如下:7TAHTML5中文学习网 - HTML5先行者学习网

  ?7TAHTML5中文学习网 - HTML5先行者学习网

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标记的。由于不要相信代码输入,所以在代码中要做检查(比如说检查这里的有没有子标签)。7TAHTML5中文学习网 - HTML5先行者学习网

  解析代码如下:7TAHTML5中文学习网 - HTML5先行者学习网

  ?7TAHTML5中文学习网 - HTML5先行者学习网

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程序设计有所帮助。7TAHTML5中文学习网 - HTML5先行者学习网

(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助