我正在尝试使用 xpath 查找 xml 中的元素。这是我的代码:
utf8_parser = etree.XMLParser(encoding='utf-8')
root = etree.fromstring(someString.encode('utf-8'), parser=utf8_parser)
somelist = root.findall("model/class[*/attributes/attribute/@name='var']/@name")
someString 中的 xml 如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<model>
<class name="B" kind="abstract">
<inheritance>
<from name="A" privacy="private" />
</inheritance>
<private>
<methods>
<method name="f" type="int" scope="instance">
<from name="A" />
<virtual pure="yes" />
<arguments></arguments>
</method>
</methods>
</private>
<public>
<attributes>
<attribute name="var" type="int" scope="instance">
</attribute>
</attributes>
</public>
</class>
</model>
当我使用 findall
时,我收到此错误:
raise SyntaxError("invalid predicate")
SyntaxError: invalid predicate
我尝试使用xpath
而不是findall
。该脚本运行没有错误,但 somelist
为空。我做错了什么?
最佳答案
从xpath()
切换到findall()
并不是一个解决方案。后者仅支持 XPath 1.0 表达式的子集(与 xml.etree.ElementTree
的 XPath support 兼容),并且您尝试的表达式恰好是不支持的子集的一部分。
实际问题是,root
变量已经引用了 model
元素,因此您无需在中再次提及 "model"
你的 XPath :
somelist = root.xpath("class[*/attributes/attribute/@name='var']/@name")
关于python - lxml findall 语法错误 : invalid predicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36674120/