Parsing XML with javascript

admin

Administrator
Staff member
Hi there, am currently trying to implement some proof of concept ajax code in my website at the moment and am struggling with some of the parsing of the xml.

E.g., I have the following XML file:

<results>
<client>
<forename>Jim</forename>
<surname>Smith</surname>
<number>1234</number>
</client>
<client>
<forename>Susan</forename>
<surname>Sanders</surname>
<number>984</number>
</client>
<client>
<forename>Henry</forename>
<surname>Cooper</surname>
<number>982</number>
</client>
</results>

These are the results of an embeded search. We have the code to generate the XML file already in the site and what I want to do is parse that xml file, run through each client and pull out the elements individually by name. I can get the code to work to pull out all of the elements sequentially, but I cant work out how to access each client in turn and access the attributes by name.

The following will pull all of them out:


var output='';
var clients = xmlObj.getElementsByTagName('client');
for (i=0;i<clients.length;i++) {
output += '<h1>Client</h1>';
for (j=0;j<clients.childNodes.length;j++) {
if (clients.childNodes[j].nodeType != 1) continue;
output += clients.childNodes[j].firstChild.nodeValue + '<br>';
}
}


But what I want to do is something along the lines of:


for (i=0;i<clients.length;i++) {
output += '<h1>Client</h1>';
output += clients.<ACCESS THE ELEMENT NAMED>('forename').value;
}


Hope that makes sense, any help would be greatly appreciated. I have tried using getElementByTag, getAttribute and some others but it says they arent functions of the clients and I am kind of guessing as I havent been able to find a tutorial that does what I want.

Thanks
 
Back
Top