20 December, 2010

Parse XML using Javascript

It is quite easier to parse XML using Javascript. Most of the browsers have XML parsers for manipulating XML. But, prior to parsing the XML it must first be loaded to XML DOM object, which can then be accessed with Javascript. Since for some security reasons, browsers do not allow access across domains, both the page and the xml it is trying to load should be in same server.

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 nodes we can do as:

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: