您可以使用这个简单的XPath检查元素是否存在(replace
fileX.xml
). 如果元素存在于给定的XML文件中,XPath表达式只返回非空结果。在下面的例子中,测试从非常具体到更一般:
from lxml import etree
print("Checking variants...")
root = etree.parse("fileX.xml")
if root.xpath('/memberdef[param[type/ref and declname]]'):
print("Third variant.")
elif root.xpath('/memberdef[param[type and declname]]'):
print("Second variant.")
elif root.xpath('/memberdef/param[type]'):
print("First variant.")
else:
print("None of the given variants.")
所以呢
-
memberdef
元素具有
param
有孩子的孩子
type/ref
孩子和孩子
declname
-
成员定义
有孩子的孩子
type
declname公司
-
第三个IF检查
成员定义
有孩子的孩子
类型
孩子。