简体   繁体   中英

How to read CDATA from xml file with Python

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:

<content><![CDATA[Jaguar XKR 
new tires 
perfect condition 
Black LeatherInterior]]></content>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM