lxml findall SyntaxError:谓词无效 [英] lxml findall SyntaxError: invalid predicate

查看:118
本文介绍了lxml findall SyntaxError:谓词无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用xpath在xml中查找元素.这是我的代码:

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")

someString中的

xml看起来像:

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>

当我使用findall时,出现此错误:

When Im using findall I got this error:

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

我尝试使用xpath而不是findall.该脚本运行无错误,但somelist为空.我在做什么错了?

I tried to use xpath instead of findall. The script runs without errors but the somelist is empty. What am I doing wrong?

推荐答案

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

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.

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

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")

这篇关于lxml findall SyntaxError:谓词无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆