tags:

views:

33

answers:

1

Having gotten such a XML document with the help of ajax (var data = request.responseXML;), how do I parse the contacts?:

<?xml version="1.0" encoding="UTF-8"?>
<Alladresses xmlns="http://somedomain.org/doc/2007-08-02/"&gt;
 <Owner>
  <ID>gut74hfowesdfj49fjsifhryh8e8rta3uyhw4</ID>
  <Name>Mr.Bin</Name>
 </Owner>
 <Contacts>
  <Person>
   <Name>Greg</Name>
   <Phone>3254566756</Phone>
  </Person>
  <Person>
   <Name>Smith</Name>
   <Phone>342446446</Phone>
  </Person>
  <Person>
   <Name>Yuliya</Name>
   <Phone>675445566867</Phone>
  </Person>
 </Contacts>
</Alladresses>
A: 

request.responseXML gives you an XML Document node. This works similarly to the HTML DOM (in fact, the HTML DOM is an extension of the plain XML DOM ‘Core’), so you can use many of the same methods you would on HTML nodes, eg.:

var doc= request.responseXML;
var contacts= doc.getElementsByTagName('Contacts')[0];
var people= contacts.getElementsByTagName('Person');

var details= [];
for (var i= 0; i<people.length; i++) {
    var person= people[i];
    var name= person.getElementsByTagName('Name').firstChild.data;
    var phone= person.getElementsByTagName('Phone').firstChild.data;
    details.push({name: name, phone: phone});
}

naturally there are many ways you can make this sort of parsing job more robust and generic, helpful libraries, XPath support, and so on. But in basic nature it is little different from HTML DOM work.

bobince