繁体   English   中英

Python LXML etree检查节点是否存在

[英]Python lxml etree check if node exists

我有这个XML:

<MasterPage>
    <NextPage>
        <prefix>

我想检查prefix节点是否存在; 我试过了,但是没有用:

self.doc=etree.parse(xmlFile)
if hasattr(self.doc, 'MasterPage/NextPage/prefix'):
>>> from lxml.html import fromstring
>>> import lxml.html as PARSER
>>> data = """<MasterPage>
...              <NextPage>
...                  <prefix>"""
>>> root = PARSER.fromstring(data) 
>>> node_list = []
>>> for ele in root.getiterator():
...     node_list.append(ele.tag)
... 
>>> if "prefix" in node_list:
...     print "True"
... 
True
>>> node_list
['masterpage', 'nextpage', 'prefix']

您可以使用etree库中的find()或findall()函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM