The XML2jsobj Function
We’ll now define an Add() function within XML2jsobj. This appends a name/value pair to the data object, e.g. data[name] = value. However, if that name already exists, it must convert data[name] to an array so two or more values can be applied:
We now require a loop to examine the XML node’s attributes (e.g. <node attrib1="1" attrib2="2">) and append them to the data object using the Add() function:
The next loop examines all child nodes. Comments and white space are ignored but, if a child contains a single item of textual data, it’s appended to the data object using Add(). If that child has its own children, we recursively call XML2jsobj to generate the object:
Finally, we return the data object to our calling function:
Our Ajax call can retrieve XML from a web service:
So, if example.xml returned the following XML data:
XML2jsobj(xhr.responseXML.documentElement) would return the following object:
You can therefore use obj.status.text to retrieve the “Hello!” text.
A few notes about XML2jsobj:
Grab the Code
Please download the code and examples for your own projects.