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
但問題是雙重的。首先,這包括我不感興趣的文本。其次,它所做的只是打印文本。我不知道如何只打印特定的文本,或編寫代碼將文本返回爲一個字符串,我可以將其分配給一個變量並稍後使用。我甚至不知道如何開始提取我感興趣的屬性。
有誰知道如何解決這個問題?而且我更喜歡一個涉及薩克斯解析器的解決方案,因爲我至少對它的工作原理有一個模糊的理解。
非常感謝您提供快速,非常詳細的答案。我會試一試! – Scheherazade 2013-03-02 18:43:19