【发布时间】:2022-01-20 21:21:04
【问题描述】:
我正在尝试使用 XPath 获取 SVG 文件中的元素。我尝试了以下代码,但 singleNodeValue 为空。 doc 似乎是正确的,所以我猜evaluate() 参数或 XPath 是错误的,但我找不到任何错误。为什么它不起作用?
JavaScript
fetch('test.svg')
.then(response => response.text())
.then(data=>{
const parser = new DOMParser();
const doc = parser.parseFromString(data, "text/xml");
console.log(doc);
const res = doc.evaluate("//symbol[@label='square']", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
console.log(res.singleNodeValue);
})
SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<symbol label ="square">
<rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
</symbol>
</svg>
经过一些测试,我发现如果我删除xmlns="http://www.w3.org/2000/svg",它会起作用。我在网上搜索了一下,找到了答案:Why XPath does not work with xmlns attribute
【问题讨论】:
-
你能解释一下提取标签的目的是什么吗?
-
@Dementic 当 SVG 包含多个图像时仅显示选定的图像。问题中的 SVG 仅用于说明;不是我尝试使用的真正的 SVG。
标签: javascript xml xpath