gpt4 book ai didi

Python lxml xpath XPathEvalError : Invalid expression -- why?

转载 作者:行者123 更新时间:2023-12-02 12:42:24 26 4
gpt4 key购买 nike

我正在尝试使用 lxml 解析 SVG 文档。这是我的代码:

nsmap = {
'svg': 'http://www.w3.org/2000/svg',
'xlink': 'http://www.w3.org/1999/xlink',
}

root = etree.XML(svg)

# this works (finds the element with the given ID)
root.xpath('./svg:g/svg:g/svg:g[@id="route_1_edge"]', namespaces=nsmap)

# this yields "XPathEvalError: Invalid expression"
root.xpath('./svg:g/svg:g/svg:g[fn:startswith(@id,"route_1")]', namespaces=nsmap)

有人知道为什么第一个有效而第二个无效吗?如果我将第三个 svg:g 更改为 svg:text 我不会收到异常,所以它似乎与 g 有关code> 元素特别是它不喜欢的,不过,简单的 g[@id="foo"] 搜索工作正常。

最佳答案

“startswith”函数拼写为 starts-with 。另外,省略 fn:

root.xpath('./svg:g/svg:g/svg:g[starts-with(@id,"route_1")]', namespaces=nsmap)
<小时/>
import lxml.etree as etree
import lxml.builder as builder

nsmap = {
'svg': 'http://www.w3.org/2000/svg',
'xlink': 'http://www.w3.org/1999/xlink',
}

E = builder.ElementMaker(
namespace='http://www.w3.org/2000/svg',
nsmap=nsmap)

root = (
E.root(
E.g(
E.g(
E.g(id = "route_1_edge" )))))

print(etree.tostring(root, pretty_print=True))
print(root.xpath('./svg:g/svg:g/svg:g[@id="route_1_edge"]', namespaces=nsmap))
print(root.xpath('./svg:g/svg:g/svg:g[starts-with(@id,"route_1")]', namespaces=nsmap))

产量

<svg:root xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<svg:g>
<svg:g>
<svg:g id="route_1_edge"/>
</svg:g>
</svg:g>
</svg:root>

[<Element {http://www.w3.org/2000/svg}g at 0xb7462c34>]
[<Element {http://www.w3.org/2000/svg}g at 0xb7462be4>]

关于Python lxml xpath XPathEvalError : Invalid expression -- why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15487106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com