Parsing Childnode values in javascript

63 Views Asked by At

I have an XML

<root><example><examplevalue>exampletext</examplevalue><examplevalue>exampletext2</examplevalue</example></root>

and I have the following javscript code

            if (window.DOMParser){ // Standard browsers
                var parser = new DOMParser();
                xmlDoc = parser.parseFromString(xmlString, "text/xml");
            }
            else { // Internet Explorer
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.loadXML(xmlString); 
            }
            var coll=xmlDoc.getElementsByTagName("example");
            console.log(coll[0].childNodes[0].nodeValue);

The console output is

null

I would expect it to be

exampletext

Why are the childnodes not parsed correctly? childNodes seems to be a method of class node. But the getElementByName return a HTMLCollection object. How does that work? Thanks for any hints.

2

There are 2 best solutions below

0
Abdullah Ceylan On

It because you fell into window.DOMParser condition. For DOMParser you need to use textContent.

In your case, you can create a function called getNodeValue and pass the node. Then get which one is available.

const getNodeValue = (node) => node.nodeValue || node.textContent;

 if (window.DOMParser){ // Standard browsers
  var parser = new DOMParser();
  xmlDoc = parser.parseFromString(xmlString, "text/xml");
}
else { // Internet Explorer
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(xmlString); 
}
var coll=xmlDoc.getElementsByTagName("example");
console.log(getNodeValue(coll[0].childNodes[0]))
// output => examplecontent
1
Rory On

you need to navigate to it using the childNodes property to access the value of the first <examplevalue> element then access its textContent property

if (window.DOMParser) { // Standard browsers
  var parser = new DOMParser();
  xmlDoc = parser.parseFromString(xmlString, "text/xml");
} else { // Internet Explorer
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(xmlString); 
}

var exampleValues = xmlDoc.getElementsByTagName("examplevalue");
console.log(exampleValues[0].textContent);