如何使用 python SAX 解析器获取标签之间的文本? [英] How can I get the text between tags using python SAX parser?
本文介绍了如何使用 python SAX 解析器获取标签之间的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要的只是获取相应标签的文本并将其持久化到数据库中.由于 xml 文件很大(4.5GB),我使用的是 sax.我使用 characters 方法来获取文本并将其放入字典中.但是,当我在 endElement 方法中打印文本时,我得到了一个新行而不是文本.
What I need is just get the text of the corresponding tag and persist it into database. Since the xml file is big (4.5GB) I'm using sax. I used the characters method to get the text and put it in a dictionary. However when I'm printing the text at the endElement method I'm getting a new line instead of the text.
这是我的代码:
def characters(self,content):
text = unescape(content))
self.map[self.tag]=text
def startElement(self, name, attrs):
self.tag = name
def endElement (self, name)
if (name=="sometag")
print self.map[name]
提前致谢.
推荐答案
标签中的文本由 SAX 处理器分块.characters
可能会被多次调用.
The text in the tag is chunked by the SAX processor. characters
might be called multiple times.
您需要执行以下操作:
def startElement(self, name, attrs):
self.map[name] = ''
self.tag = name
def characters(self, content):
self.map[self.tag] += content
def endElement(self, name):
print self.map[name]
这篇关于如何使用 python SAX 解析器获取标签之间的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文