A clean, simple and effective way to access your XML data with JavaScript.

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 clean or efficient thing to do.

With the growing of HTML5, Ajax, JavaScript libraries, and mobile devices, is was a question of time until I'll need a simple and fast way to access XLM data.

After check around internet, and see the size and complexity of other xml parsers online, and basicly, because I din't manage to get them to work with my xml structure, I decide that should be so complicated to transform my old xml2array parser in actionscript 2, to javascript, and for my surprise, was increadible easy and streight forward.

For the XML I'm usually working with, it's possible to run them through a recursive function to get a simple array object in return, which is much easier to work with.

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

function readNode(baseNode,output)
  {
  var node = baseNode.firstChild;

  if (output==undefined) var output = {};
  
  while(node)
    {
    // CREATE THE OBJECT
    var nodeData = {};

    // STORE NODE ATTRIBUTES
    if (node.attr)
      {
      var nNodes = node.attr.length;
      while(nNodes--)
        nodeData['$'+node.attr[nNodes].nodeName] = node.attr[nNodes].nodeValue;
      }      

    // CREATE THE NODES ARRAY
    if (output[node.nodeName]==undefined)
	  output[node.nodeName] = new Array(nodeData);
    else
	  output[node.nodeName].push(nodeData);

    // GET SUBELEMENTS ( enter in the node >> recursive )
    var id = output[node.nodeName].length-1;
    output[node.nodeName][id] = readNode(node,output[node.nodeName][id])

    // GET #TEXT NODE
    if (node.firstChild) nodeData['#text'] = node.firstChild.nodeValue;

    // NEXT NODE
    node = node.nextSibling;
    }
  
  return output;
  }

So for example, if your XML is like this:

<data>
  <library>
    <Book name="Mary Poppins" />
    <Book name="Sphere" >
      Book description...	
    </Book>
  </library>
</data>

We run our function over the XmlHttp.responseXml:

var xmlArray = readNode([Our XmlHttp.responseXml]);

and then we can access, lets say the second register properties with the JavaScript structure:

xmlArray['library'][0]['Book'][1].$name     //  returns 'Sphere'
xmlArray['library'][0]['Book'][1]['#text']  //  return 'Book description...'
Download: XML2Array function and Example