问题
I'm trying to find elements in xml using xpath. This is my code:
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")
xml in someString looks like:
<?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>
When Im using findall
I got this error:
raise SyntaxError("invalid predicate")
SyntaxError: invalid predicate
I tried to use xpath
instead of findall
. The script runs without errors but the somelist
is empty. What am I doing wrong?
回答1:
Switching from xpath()
to findall()
is not a solution. The latter only supports subset of XPath 1.0 expression (compatible to xml.etree.ElementTree
's XPath support), and your attempted expression happen to be part of the unsupported subset.
The actual problem is, that root
variable already references model
element, so you don't need to mention "model"
again in your XPath :
somelist = root.xpath("class[*/attributes/attribute/@name='var']/@name")
来源:https://stackoverflow.com/questions/36674120/lxml-findall-syntaxerror-invalid-predicate