python解析xml

来源:互联网 发布:.net编程委托有什么用 编辑:程序博客网 时间:2024/05/17 08:59

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-16import xml.dom.minidomdom = 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........................"