我尝试使用lxml在Python中解析XML文件,如下所示:
objectify.parse(xmlPath, parserWithSchema)
但XML文件可能在奇怪的地方包含注释:
<root>
<text>Sam<!--comment-->ple text</text>
<!--comment-->
<float>1.2<!--comment-->3456</float>
</root>
这是一种在解析之前不加载或删除注释的方法?
在解析器上设置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)
希望能有所帮助。