2

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

如何防止 SAX 这种行为。

示例with_amp.xml

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

蟒蛇处理程序:

from xml.sax import handler, parse

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

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

我希望输出为:

One Two
One &amp;mdash;  Two
4

1 回答 1

0

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

例如,您的信息:

print(content)

会变成

print(saxutils.escape(content))

(不过,您需要将 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())
于 2014-04-10T14:31:41.343 回答