[英]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.