代码之家  ›  专栏  ›  技术社区  ›  Damn Vegetables

Document.eevaluate()从命名空间解析程序获取默认名称空间

  •  0
  • Damn Vegetables  · 技术社区  · 2 年前

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

    如果我跑步 console.log(ns.lookupNamespaceURI("")); console.log(ns.lookupNamespaceURI(null)); ,它返回 http://www.w3.org/2000/svg ,这是 xmlns SVG的值。那么,为什么代码找不到的元素 "//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>
    
    0 回复  |  直到 2 年前
        1
  •  0
  •   Martin Honnen    2 年前

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