if(window.ActiveXObject){
var doc=new ActiveXObject("Microsoft.XMLDOM");
doc.async="false";
doc.load("XMLFile.xml");
}
else if(document.implementation&&document.implementation.createDocument){
var parser=new DOMParser();
var doc=parser.parseFromString("XMLFile.xml", "text/xml");
}
else{
throw new Error("XML DOM is not supported!");
}
var rs="";
var name;
var x=doc.getElementsByTagName('person');
for(var i=0; i< x.length; i++){
name=x[i].firstChild.firstChild.nodeValue;
rs+=name + ", ";
}
document.write(rs);
//why doesn't it work? Nothing is displayed in the browser. Why??
//Help!!
tries to fetch the first child of the first child in every 'person' node - in other words, a node contained within the first child node - and there aren't any. Each 'person' node in your data contains three child simple nodes. If you want the 'name' node, loop through those child nodes until you find it.
There is different node types and some « illegitime nodes » like carriage returns, tabs or other specials characters which are to avoid to work with element Nodes (see, for example, this page about the different node Types).
Then the two different following syntax give with Mozilla FireFox different firstChild Nodes !
Code:
// First syntax with line feed and carriage return
<person>
<name>A</name>
<!-- -->
</person>
// Second syntax without characters between the two element Nodes
<person><name>A</name>
<!-- -->
</person>
Then to get the first element Node of your person tag (even if the code contains comments), you have to make something like this
Code:
var j=0,x=doc.getElementsByTagName('person');
while (x.childNodes[j].nodeType!=1) j++;
var xFirstElementNode=x.childNodes[j];
Bookmarks