简体   繁体   English

lxml findall 语法错误:谓词无效

[英]lxml findall SyntaxError: invalid predicate

I'm trying to find elements in xml using xpath.我正在尝试使用 xpath 在 xml 中查找元素。 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: 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>

When Im using findall I got this error:当我使用findall我收到此错误:

raise SyntaxError("invalid predicate")
SyntaxError: invalid predicate

I tried to use xpath instead of findall .我尝试使用xpath而不是findall The script runs without errors but the somelist is empty.脚本运行没有错误,但somelist为空。 What am I doing wrong?我究竟做错了什么?

Switching from xpath() to findall() is not a solution.xpath()切换到findall()不是解决方案。 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.后者仅支持 XPath 1.0 表达式的子集(与xml.etree.ElementTreeXPath 支持兼容),而您尝试的表达式恰好是不受支持的子集的一部分。

The actual problem is, that root variable already references model element, so you don't need to mention "model" again in your XPath :实际问题是, root变量已经引用了model元素,因此您无需在 XPath 中再次提及"model"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM