`
iihero
  • 浏览: 249950 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

用python来解析xml文件(简单情况)

阅读更多

首先,sax解析最直观,当然,也可以容许xml文件出些错。

先给定一个xml文件book.xml,

<catalog>
<bookisbn="0-596-00128-2">
<title>Python&amp;XML</title>
<author>Jones,Drake</author>
</book>
<bookisbn="0-596-00085-5">
<title>ProgrammingPython</title>
<author>Lutz</author>
</book>
<bookisbn="0-596-00281-5">
<title>LearningPython</title>
<author>Lutz,Ascher</author>
</book>
<bookisbn="0-596-00797-3">
<title>PythonCookbook</title>
<author>Martelli,Ravenscroft,Ascher</author>
</book>
<!--imaginemoreentrieshere-->
</catalog>

写一个BookHandler, 如下:

#-*-coding:utf-8-*-

importxml.sax.handler

classBookHandler(xml.sax.handler.ContentHandler):
def__init__(self):
self.inTitle
=0#handleXMLparserevents
self.mapping={}#astatemachinemodel

defstartElement(self,name,attributes):
ifname=="book":#onstartbooktag
self.buffer=""#saveISBNfordictkey
self.isbn=attributes["isbn"]
elifname=="title":#onstarttitletag
self.inTitle=1#savetitletexttofollow

defcharacters(self,data):
ifself.inTitle:#ontextwithintag
self.buffer+=data#savetextifintitle

defendElement(self,name):
ifname=="title":
self.inTitle
=0#onendtitletag
self.mapping[self.isbn]=self.buffer#storetitletextindict

importxml.sax
importpprint

parser
=xml.sax.make_parser()
handler
=BookHandler()
parser.setContentHandler(handler)
parser.parse(
'book.xml')

pprint.pprint(handler.mapping)

结果如下:

Process started >>>
{u'0-596-00085-5': u'Programming Python',
u'0-596-00128-2': u'Python & XML',
u'0-596-00281-5': u'Learning Python',
u'0-596-00797-3': u'Python Cookbook'}<<< Process finished.
================ READY ================

不过,这是比较简单的情况了。而且我们可以看到,结果全是以unicode串输出的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics