如何在lxml中解析XML时不加载注释

seb*_*szw 11 python xml lxml comments xml-parsing

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

objectify.parse(xmlPath, parserWithSchema)
Run Code Online (Sandbox Code Playgroud)

但XML文件可能包含奇怪的地方的评论:

<root>
    <text>Sam<!--comment-->ple text</text>
    <!--comment-->
    <float>1.2<!--comment-->3456</float>
</root>
Run Code Online (Sandbox Code Playgroud)

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

ale*_*cxe 15

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

from lxml import etree, objectify

parser = etree.XMLParser(remove_comments=True)
tree = objectify.parse(xmlPath, parser=parser)
Run Code Online (Sandbox Code Playgroud)

或者,使用makeparser()方法:

parser = objectify.makeparser(remove_comments=True)
tree = objectify.parse(xmlPath, parser=parser)
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.