[英]lxml findall SyntaxError: invalid predicate
我正在尝试使用 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 支持兼容),而您尝试的表达式恰好是不受支持的子集的一部分。
实际问题是, root
变量已经引用了model
元素,因此您无需在 XPath 中再次提及"model"
:
somelist = root.xpath("class[*/attributes/attribute/@name='var']/@name")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.