如何强制SAX解析器不转换XML实体?

2024-09-26 17:42:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用SAX解析大型xml文件。 但它将每个XML code转换为它的符号版本。在

如何防止SAX这种行为。在

示例with_amp.xml: 在

<?xml version="1.0" encoding="utf-8"?>
<root>
  <title>One Two</title>
  <title>One &amp;mdash;  Two</title>
</root>

python处理程序: 在

^{pr2}$

我希望输出是: 在

One Two
One &amp;mdash;  Two

Tags: 文件版本示例titlewith符号coderoot
1条回答
网友
1楼 · 发布于 2024-09-26 17:42:48

使用saxutils,我成功地做到了。 https://docs.python.org/2/library/xml.sax.utils.html#module-xml.sax.saxutils

例如,关于您的信息:

print(content)

会变成

^{pr2}$

(您需要将saxutils添加到导入中: 整个过程都会

from xml.sax import handler, parse, saxutils

class Handler(handler.ContentHandler):
    def characters(self, content):
        if content.isspace(): return
        print(saxutils.escape(content))

if __name__ == "__main__":
    parse(open('with_amp.xml', 'r'), Handler())

相关问题 更多 >

    热门问题