本文实例讲述了python解析xml文件的方法。分享给大家供大家参考。具体如下:
python解析xml非常方便。在dive into python中也有讲解。
如果xml的结构如下:
zoer think in java this is a good book naughty gone with the wind this is a good book 2 cc this is a good book 3
第三个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程序设计有所帮助。