lxml findall SyntaxError:无效的谓词

时间:2016-04-17 08:07:08

标签: python xml xpath lxml

我试图使用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为空。我做错了什么?

1 个答案:

答案 0 :(得分:1)

xpath()切换到findall()不是解决方案。后者仅支持XPath 1.0表达式的子集(与xml.etree.ElementTree的{​​{3}}兼容),并且您尝试的表达式恰好是不受支持的子集的一部分。

实际问题是,root变量已经引用了model元素,因此您无需在XPath中再次提及"model"

somelist = root.xpath("class[*/attributes/attribute/@name='var']/@name")
相关问题