Search This Blog

Monday, June 30, 2008

Javascript XML Parsing

//Create a XMLDoc object from the xml string.
function getXMLDocObject(xmlstr) {
var xmlDoc;
try { //Internet Explorer
try {
xmlDoc=new ActiveXObject("MSXML2.DOMDocument");
} catch(e) {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
xmlDoc.async="false";
xmlDoc.loadXML(xmlstr);
} catch(e) {
try { //Firefox, Mozilla, Opera, etc.
parser=new DOMParser();
xmlDoc=parser.parseFromString(xmlstr,"text/xml");
} catch(e) {
alert(e.message)
}
}
return xmlDoc;
}

/* Consider the following XML

<?xml version="1.0" encoding="utf-8"?>
<rootnode>
<error value='true'>
<message>this is the message</message>
</error>
</rootnode>
*/

// Create XMLDoc object
xmlDoc = getXMLDocObject(asyncreq.responseText);

// Get root node
var root = xmlDoc.getElementsByTagName('rootnode')[0];

/* You can loop over all child nodes of root using root.childNodes and root.childNodes.length */

// Will alert "error"
alert(root.childNodes[1].nodeName);

// Will alert "true";
alert(root.childNodes[1].getAttribute('value'));

// Will alert "message";
alert(root.childNodes[1].childNodes[1].nodeName);

// Will alert "this is the message".
alert(root.childNodes[1].childNodes[1].childNodes[0].nodeValue);