Click to See Complete Forum and Search --> : Parsing XML with javascript


Kronenbourg
05-12-2006, 11:45 AM
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[i].childNodes.length;j++) {
if (clients[i].childNodes[j].nodeType != 1) continue;
output += clients[i].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[i].<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[i] and I am kind of guessing as I havent been able to find a tutorial that does what I want.

Thanks

Stephen Philbin
05-12-2006, 12:33 PM
I think what you're looking for is something allong the lines of if(nodeVariable.nodeName == 'forename')
{do whatever;}

Though if you're working on XML documents, you may need to use localName instead of nodeName. localName will return a string containing only the local part of the node name and omit the namespace. Also, the nodeName may give other information depending on the node type. It will give the name of the element if it is an element, but bay return other information if used on non element type nodes.

Hope that helps and good luck! ;)