如何使用Python从xml文件中读取CDATA

时间:2014-09-30 12:48:43

标签: python xml cdata

我尝试用Python解析一个大的xml文件,但是当我想要打印CDATA信息时,没有什么,特别是描述的“content”标签

我的源代码如下所示:

#!/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"

内容标记如下所示:

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

提前致谢

1 个答案:

答案 0 :(得分:1)

可以多次调用.characters()函数,每次都使用文本片段。您似乎每次调用都会覆盖self.description

试试这个:

def characters(self, content):
    ...
    self.description += content  # Note: '+=', not '='
    ...

并记得在完成后设置self.description = ""