Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get a list of nodes as a result of a XPath in JavaScript, but do not know how to do it. Unfortunately, I have tried a lot without any knowledge of how to do it - the alert does not come.

So how to get a list of nodes from evaluate?

<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ccts="urn:oasis:names:specification:ubl:schema:xsd:CoreComponentParameters-2" xmlns:sdt="urn:oasis:names:specification:ubl:schema:xsd:SpecializedDatatypes-2" xmlns:udt="urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2" 
xmlns:xsi="" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 UBL-Invoice-2.0.xsd">

What I have tried:

var parser = new DOMParser();
var xml = parser.parseFromString(data.d.FXml, "text/xml");

var resolver = null;
var xpath;
var ns = xml.children[0].getAttribute("xmlns:xsi");
if (ns) {
    resolver = function () {
        return ns;
    xpath = "defaultnamespace:" + xpath;

var es = xml.evaluate("/ContractDocumentReference[ID='234']", xml, resolver, XPathResult.ANY_TYPE, null);

var node = null;
while (node = es.iterateNext()) {
Updated 1-Nov-23 10:18am

1 solution

To retrieve a list of nodes using XPath in JavaScript, you can try using the document.evaluate() method. This updated code snippet will select all cac:ContractDocumentReference nodes with cbc:ID equal to '234' from the provided XML. Adjust the XPath expression and the node parsing logic based on your specific requirements.
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
const select = xpath => {
  const resolver = xmlDoc.createNSResolver(xmlDoc.documentElement);
  const result = xmlDoc.evaluate(

  const nodes = [];
  let node = result.iterateNext();
  while (node) {
    node = result.iterateNext();
  return nodes;

const nodes = select("//cac:ContractDocumentReference[cbc:ID='234']");

nodes.forEach(node => {
  const id = node.querySelector('cbc\\:ID').textContent;
  const issueDate = node.querySelector('cbc\\:IssueDate').textContent;
  console.log(`ID: ${id}, Issue Date: ${issueDate}`);
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900