2013-03-02 42 views
1

我有一個看起來像這樣的XML文件:如何使用python sax解析器將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> 

我需要的是某種方式得到「文字我想用」和「更多的文字我想用」,但不是「文字我m不感興趣「的字符串形式,稍後可以被某些任意函數使用。我還需要以字符串的形式得到「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 

但問題是雙重的。首先,這包括我不感興趣的文本。其次,它所做的只是打印文本。我不知道如何只打印特定的文本,或編寫代碼將文本返回爲一個字符串,我可以將其分配給一個變量並稍後使用。我甚至不知道如何開始提取我感興趣的屬性。

有誰知道如何解決這個問題?而且我更喜歡一個涉及薩克斯解析器的解決方案,因爲我至少對它的工作原理有一個模糊的理解。

回答

0

想法是在遇到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會更容易些。

+0

非常感謝您提供快速,非常詳細的答案。我會試一試! – Scheherazade 2013-03-02 18:43:19

相關問題