How to not load the comments while parsing XML in lxml

*爱你&永不变心* 提交于 2019-11-27 17:51:37

问题


I try to parse XML file in Python using lxml like this:

objectify.parse(xmlPath, parserWithSchema)

but XML file may contains comments in strange places:

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

It is a way to not load or delete comments before parsing?


回答1:


Set remove_comments=True on the parser (documentation):

from lxml import etree, objectify

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

Or, using the makeparser() method:

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

Hope that helps.



来源:https://stackoverflow.com/questions/18313818/how-to-not-load-the-comments-while-parsing-xml-in-lxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!