Very Basic JavaScript xml2array

The following JavaScript code is a very basic function for converting an XmlHttp.responseXml object into a simple array:

function xml2array(xmlDoc) {
var node = new Object();

if(xmlDoc.nodeName == "#document") {
node[xmlDoc.childNodes[0].nodeName] = xml2array(xmlDoc.childNodes[0]); //assume always only 1 child node of a document
} else {
if(xmlDoc.childNodes.length == 0) { //no children and no value, set to null
node = null;
} else if(xmlDoc.childNodes.length == 1 && xmlDoc.childNodes[0].nodeName == "#text"){
node = xmlDoc.childNodes[0].nodeValue;
} else {
var hasAttribute = false;
for(var i = 0; i < xmlDoc.childNodes.length; i++) {
var child = xmlDoc.childNodes[i];
if(child.attributes && child.attributes.length) {
hasAttribute = true;
break;
}
}

if(hasAttribute) { //nodes in this series have attributes, lets treat them as an array
var arr = new Array();
for(var i = 0; i < xmlDoc.childNodes.length; i++) {
var child = xmlDoc.childNodes[i];
arr[i] = xml2array(child);
}
node[xmlDoc.childNodes[0].nodeName] = arr;
} else { //no attributes, consider each node as unique name element
for(var i = 0; i < xmlDoc.childNodes.length; i++) {
var child = xmlDoc.childNodes[i];
node[child.nodeName] = xml2array(child);
}
}
}
}
return node;
}
Why would you want to use this? If you're building an Ajax app in which you actually process raw XML data in your JavaScript code, then you'd probably agree that working with XML in JavaScript is not the most efficient thing (in terms of lines of code or readability). If your XML responses are simple enough on the other hand, it's possible to run them through the above generic function to get a simple array object in return, which is much easier to work with.

Note that the above is very limited and will only work with very basic XML structures, namely:
  • The response document must have only one root element. Others will be ignored (at best).
  • The XML document must consist of simple element names only.
  • If an element contains sub-elements with attributes, then the whole element is considered as a list with all sub-elements as list items. The first element name is used as the list name. (Try it out or read the code to see what I mean.)
These assumptions were built around my specific needs. For a slightly more comprehensive solution, have a look at this library. I started out with this one, which was working great, but I hit an inconsistency in the way it treats single-element lists which was breaking my code. I couldn't figure out what the problem was so I wrote the above function instead.

Comments

  1. do you think you can pair this with an XmlHttpRequest? I have not seen even *1* example on the web that does.

    ReplyDelete

Post a Comment

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word