12

我尝试使用 lxml 在 Python 中解析 XML 文件,如下所示:

objectify.parse(xmlPath, parserWithSchema)

但 XML 文件可能在奇怪的地方包含注释:

<root>
    <text>Sam<!--comment-->ple text</text>
    <!--comment-->
    <float>1.2<!--comment-->3456</float>
</root>

这是一种在解析之前不加载或删除评论的方法吗?

4

1 回答 1

19

remove_comments=True在解析器上设置(文档):

from lxml import etree, objectify

parser = etree.XMLParser(remove_comments=True)
tree = objectify.parse(xmlPath, parser=parser)

或者,使用以下makeparser()方法:

parser = objectify.makeparser(remove_comments=True)
tree = objectify.parse(xmlPath, parser=parser)

希望有帮助。

于 2013-08-19T12:34:04.823 回答