Python lxml xpath xpath xpathvaleror:无效表达式为什么?

2024-04-27 19:55:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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元素有关,特别是它不喜欢的元素,不过,简单的g[@id="foo"]搜索也很好。在


Tags: thesvgorgidhttp元素wwwroot
1条回答
网友
1楼 · 发布于 2024-04-27 19:55:18

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

root.xpath('./svg:g/svg:g/svg:g[starts-with(@id,"route_1")]', namespaces=nsmap)

^{pr2}$

收益率

<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>]

相关问题 更多 >