Search code examples
javascriptxpath

If there is an xpath expression saved in a node, is there a way to execute that statement?


In the XML document below, I am trying to figure out how to get the result of the xpath statement that is saved in node B.

<?xml version="1.0" encoding="utf-8"?>
<Example>
    <A>test1</A>
    <B>A/text()</B>
</Example>

The text value of node A is test1. The text value of node B is A/text().

I would like to execute the XPath statement from node B which will provide the value of node A.

I have tested (B/text())/text() but that did not return anything. I tried change the value of node B to A and then used statement (B/text())/text(), but that did not return anything either.


Solution

  • Assuming the browser side (DOM Level 3 XPath) evaluate method:

    const xml = `<?xml version="1.0" encoding="utf-8"?>
    <Example>
        <A>test1</A>
        <B>A/text()</B>
    </Example>`;
    
    const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
    
    const result = xmlDoc.evaluate(xmlDoc.evaluate('Example/B', xmlDoc, null, XPathResult.STRING_TYPE).stringValue, xmlDoc.documentElement, null, XPathResult.STRING_TYPE).stringValue;
    
    console.log(result);