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

Time:12-18

The following code returns null for doc.evaluate(). But it returns the correct element for the XPath //cat:symbol[@dog:label='banana']". So, I think it is not finding the default namespace.

If I run console.log(ns.lookupNamespaceURI("")); or console.log(ns.lookupNamespaceURI(null));, it returns http://www.w3.org/2000/svg, which is the xmlns value of the SVG. Then, why is the code not finding the element for "//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>

CodePudding user response:

XPath 1.0 which the browser vendors support with the evaluate function on a Document node does not have the concept of a default element namespace so while the created namespace resolver maps the empty prefix '' to a URI within the context of XPath 1.0 that has no meaning as there an element name without a prefix (e.g. foo) always selects an element with local name foo in no namespace.

  • Related