如何使用python sax解析器将XML标记之间的文本作为字符串获取和存储?



我有一个XML文件,看起来像这样:

<TAG1>
   <TAG2 attribute1 = "attribute_i_need" attribute2 = "attribute_i_dont_need" >
      Text I want to use
   </TAG2>
   <TAG3>
      Text I'm not interested in
   </TAG3>
   <TAG4>
      More text I want to use
   </TAG4>

我需要的是以某种方式获得"我想使用的文本"one_answers"我想使用的更多文本",但不是"我不感兴趣的文本",以字符串的形式,可以稍后由一些任意函数使用。我还需要以字符串的形式获得"attribute_i_need"。我以前没有真正使用过sax解析器,因此完全卡住了。我可以使用以下命令打印文档中的所有文本:

import xml.sax
class myHandler(xml.sax.ContentHandler):
    def characters(self, content):
        print (content)
parser = xml.sax.make_parser()
parser.setContentHandler(myHandler())
parser.parse(open("sample.xml", "r"))

这基本上会给我输出:

Text I want to use
Text I'm not interested in
More text I want to use

但问题是双重的。首先,这包括我不感兴趣的文本。其次,它所做的只是打印文本。我不知道如何打印特定的文本,或编写代码,将返回文本作为一个字符串,我可以分配给一个变量和以后使用。我甚至不知道如何开始提取我感兴趣的属性。

有谁知道如何解决这个问题吗?我更喜欢包含sax解析器的解决方案,因为我至少对它的工作原理有一个模糊的理解。

这个想法是在遇到TAG2或TAG4后开始保存所有字符,并在元素结束时停止。开始元素还提供了检查和保存感兴趣的属性的机会。

import xml.sax
class myHandler(xml.sax.ContentHandler):
    def __init__(self):
        self.text = []
        self.keeping_text = False
        self.attributes = []
    def startElement(self, name, attrs):
        if name.lower() in ('tag2', 'tag4'):
            self.keeping_text = True
        try:
            # must attribute1 be on a tag2 or anywhere?
            attr = attrs.getValue('attribute1')
            self.attributes.append(attr)
        except KeyError:
            pass
    def endElement(self, name):
        self.keeping_text = False
    def characters(self, content):
        if self.keeping_text:
            self.text.append(content)
parser = xml.sax.make_parser()
handler = myHandler()
parser.setContentHandler(handler)
parser.parse(open("sample.xml", "r"))
print handler.text
print handler.attributes
# [u'n', u'      Text I want to use', u'n', u'   ',
#  u'n', u'      More text I want to use', u'n', u'   ']
# [u'attribute_i_need']
我认为BeautifulSoup甚至是裸lxml更容易。