如何在lxml中解析XML时不加载注释 [英] How to not load the comments while parsing XML in lxml
本文介绍了如何在lxml中解析XML时不加载注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用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
( documentation ):
来自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)
希望有帮助。
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?
解决方案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.
这篇关于如何在lxml中解析XML时不加载注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文