Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python lxml findall语法错误:无效谓词_Python_Xml_Xpath_Lxml - Fatal编程技术网

Python lxml findall语法错误:无效谓词

Python lxml findall语法错误:无效谓词,python,xml,xpath,lxml,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如下

我正在尝试使用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>
我尝试使用
xpath
而不是
findall
。脚本运行时没有错误,但
somelist
为空。我做错了什么?

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

实际问题是,
root
变量已经引用了
model
元素,因此您不需要在XPath中再次提到
“model”

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

谢谢,现在可以用了。但是,难道没有一种不从xpath中删除模型的方法吗?问题是,我不知道xml会是什么样子,也不知道xpath中的字符串会是什么样子。现在,我必须手动检查xml和xpath,并根据给定的xml确定xpath是否正确。@T.Syk xpath应该对应于xml才能正确工作。无法使任意XPath针对任意XML工作。如果您从其他人那里收到XML和XPath,请他们修复XPath/XML。@T.Syk如果您只想以某种方式在XPath中保留“model”,则可以使用引用文档元素的轴启动XPath:
/model/class[*/attributes/attribute/@name='var']/@name
somelist = root.xpath("class[*/attributes/attribute/@name='var']/@name")