I try to parse a large xml file with Python, but when I want to print CDATA information, there are nothing, especially with the "content" tag for the description

My source code look like this:

#!/usr/bin/python

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

import xml.sax

import re

from cStringIO import StringIO

class MovieHandler( xml.sax.ContentHandler ):

def __init__(self):

self.item = {}

self.CurrentData = ""

self.url = ""

self.description = ""

self.price = ""

# Call when an element starts

def startElement(self, tag, attributes):

self.CurrentData = tag

# Call when an elements ends

def endElement(self, tag):

elif self.CurrentData == "url":

self.item["url"] = self.url

elif self.CurrentData == "content":

print 'description: ', self.description

elif self.CurrentData == "price":

if self.price:

self.price = re.sub('[^0-9]','',self.price[0].encode('ascii', 'ignore'))

self.item["price"] = int(self.price)

self.CurrentData = ""

print self.item

self.item.clear()

# Call when a character is read

def characters(self, content):

if self.CurrentData == "url":

self.url = content

elif self.CurrentData == "content":

self.description = content

elif self.CurrentData == "price":

self.price = content

if ( __name__ == "__main__"):

# create an XMLReader

parser = xml.sax.make_parser()

# turn off namepsaces

parser.setFeature(xml.sax.handler.feature_namespaces, 0)

# override the default ContextHandler

Handler = MovieHandler()

parser.setContentHandler(Handler)

parser.parse("myfile.xml")

print "done"

the content tag look like this:

new tires

perfect condition

Black LeatherInterior]]>

Thanks in advance

解决方案

The .characters() function can be called several times, each time with a fragment of the text. You seem to be overwriting self.description with each call.

Try this:

def characters(self, content):

...

self.description += content # Note: '+=', not '='

...

and remember to set self.description = "" when you are done with it.

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐