lxml findall SyntaxError: invalid predicate

五迷三道 提交于 2019-12-11 12:37:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!