lxml-xpath()函数不适用于正确的xpath查询



我正试图使用lxml库评估一些XPath查询,但由于某些原因,它似乎不起作用。这是代码

if __name__ == '__main__':
xml = r'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<unit xmlns="http://www.srcML.org/srcML/src" revision="0.9.5" language="Java" filename="File.java"><package>package <name><name>com</name><operator>.</operator><name>samples</name><operator>.</operator><name>e978092668</name></name>;</package>
<class><annotation>@<name>Path</name></annotation>
<specifier>public</specifier> class <name>Correct</name> <block>{
<decl_stmt><decl><annotation>@<name>Inject</name></annotation>
<specifier>private</specifier> <type><name>JsonWebToken</name></type> <name>field</name></decl>;</decl_stmt>
}</block></class>
</unit>'''.encode("UTF-8")
xpath = '''unit/class[((descendant-or-self::decl_stmt/decl[(type[name[text()='JsonWebToken']] and annotation[name[text()='Inject']])]) and (annotation[name[text()='Path']]))]'''
tree = etree.fromstring(xml)
a = tree.xpath(xpath)
print(len(a)) # returns 0 (matches)

我在freeformatter.com上用完全相同的XML字符串尝试了完全相同的xpath查询,它有效并显示了匹配。我不知道我自己的代码出了什么问题,因为在大多数情况下,我都遵循了网站上的官方教程。

编辑1:

正在尝试使用命名空间。

xpath = '''src:unit/src:class[((descendant-or-self::src:decl_stmt/src:decl[(src:type[src:name[text()='JsonWebToken']] and src:annotation[src:name[text()='Inject']])]) and (src:annotation[src:name[text()='Path']]))]'''
tree = etree.fromstring(xml)
a = tree.xpath(xpath, namespaces={
"src": "http://www.srcML.org/srcML/src"
})
print(len(a)) # returns 0 (matches)

谢谢!

问题是,当您这样做时:

tree = etree.fromstring(xml)

tree具有上下文src:unit,因此您的xpath正在src:unit中查找子src:unit。(如果是print(tree.tag),则会看到{http://www.srcML.org/srcML/src}unit。(

尝试在src:class启动xpath。。。

xpath = '''src:class[((descendant-or-self::src:decl_stmt/src:decl[(src:type[src:name[text()='JsonWebToken']] and src:annotation[src:name[text()='Inject']])]) and (src:annotation[src:name[text()='Path']]))]'''

最新更新