I am writing a XML file into a HTML file using JavaScript.
Here is the JavaScript I am using:
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","file.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("tagParent");
document.write(x.getElementsByTagName("tagChild")[0].childNodes[0].nodeValue);
The script will working for everything except for self closing xml elements (<element/>).
Example XML file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<tagParent>
<tagChild/>
</tagParent>
The script breaks and stops when it reaches a self closing tag.
What do I need to do to get it either output 0 or “”? Why is it breaking?
It is breaking because the element is empty. It doesn’t have any children so when you try to get the
nodeValueof the first child, it errors becauseundefineddoesn’t have a0property.You want something along the lines of: