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程序设计有所帮助。