Lets's say, we have an users.xml file like:
Sudhir
Bastakoti
27
John
Doe
72
Step 1: Load the XML
function loadXML(xmlFile) {
if(window.XMLHttpRequest) {
xvar = new XMLHttpRequest();
}
else {
xvar = new ActiveXObject("Microsoft.XMLHTTP");
}
xvar.open("GET", xmlFile, false);
xvar.send();
return xvar.responseXML;
}
OR, the XML can be loaded as string as well, like
function loadXMLString(xmlString) {
//here xmlString is the content of XML as string
if(window.DOMParser) {
parseIt = new DOMParser();
xDoc = parseIt.parseFromString(xmlString,"text/xml");
}
else {
xDoc = new ActiveXObject("Microsoft.XMLDOM");
xDoc.async = "false";
xDoc.loadXML(xmlString);
}
return xDoc;
}
There are some properties of DOM u.parentNode gives parent node of u, u.childNodes gives child nodes of u, u.attributes gives attributes nodes of u, u.nodeName gives name of u , u.nodeValue gives value of u
And we have a nodeType Property
Element has NodeType 1, Attribute 2, Text 3, Comment 8 and Document 9
Step 2:
To get the length of
xDoc = loadXML("books.xml");
u = xDoc.getElementsByTagName("user").length;
//it will output 2
To loop through all the nodes we can do as:
xDoc = loadXML("books.xml");
u = xDoc.documentElement.childNodes;
var details = "";
for(var i = 0; i < u.length; i++) {
details +=u[i].nodeName+": "+x[i].childNodes[0].nodeValue+"
";
}
alert(details);
No comments:
Post a Comment