Document.evaluate() 从名称space 解析器获取默认名称 space

Document.evaluate() getting default name space from namespace resolver

以下代码 returns 对于 doc.evaluate() 为空。但它 returns 是 XPath //cat:symbol[@dog:label='banana']" 的正确元素。所以,我认为它没有找到默认的命名空间。

如果我运行console.log(ns.lookupNamespaceURI("")); console.log(ns.lookupNamespaceURI(null));,它returnshttp://www.w3.org/2000/svg,也就是SVG的xmlns值。那么,为什么代码找不到 "//symbol[@dog:label='banana']" 的元素?

JavaScript

fetch('test.svg')
.then(response => response.text())
.then(data=>{
    const parser = new DOMParser();
    const doc = parser.parseFromString(data, "text/xml");
    const ns = doc.createNSResolver(doc.documentElement);
    const res = doc.evaluate("//symbol[@dog:label='banana']", doc.documentElement,
     ns, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    console.log(res.singleNodeValue);
})

test.svg

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"
 xmlns:dog="http://dog.com/dog"
 xmlns:cat="http://cat.com/cat">

    <symbol dog:label="banana">
        <rect y="10" x="10" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
    </symbol>
    <cat:symbol dog:label="banana">
        <rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
    </cat:symbol>
</svg>

浏览器供应商在 Document 节点上使用 evaluate 函数支持的 XPath 1.0 没有默认元素命名空间的概念,因此创建的命名空间解析器映射空前缀 '' 到 XPath 1.0 上下文中没有意义的 URI,因为没有前缀的元素名称(例如 foo)总是选择 中具有本地名称 foo 的元素没有 命名空间。