0

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

1
  • Your sample program doesn't run: it has syntax errors. Please reduce your program to the shortest possible program that demonstrates the error, and copy-paste that program into your question. Commented Sep 30, 2014 at 16:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.