Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript and XML iterate nodes

Status
Not open for further replies.

firsttube

Technical User
Apr 21, 2004
165
CA
I'm very new to XML, and I'm trying to parse out values from xml nodes. The xml stream being sent to the page looks like this:
Code:
<?xml version="1.0" encoding="ISO-8859-1" ?> 
<data>
 <records>
  <numrecs>2</numrecs> 
  <numfields>3</numfields> 
 </records>
 <record>
  <num>1</num> 
  <ID>1234</ID> 
  <STREET_NO>12</STREET_NO> 
  <STREET_NAME>MAIN ST</STREET_NAME> 
 </record>
 <record>
  <num>2</num> 
  <ID>124</ID> 
  <STREET_NO>14</STREET_NO> 
  <STREET_NAME>MAIN ST</STREET_NAME> 
 </record>
</data>

I'm using an XMLHttpRequest to send the request, and the page returns the xml above.

My callback function looks like this:
Code:
if (req.readyState == 4) {
 if (req.status == 200) {
    	var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
	xmldoc.async = false;
	xmldoc.loadXML(req.responseText)
	var root = xmldoc.documentElement;
  }
}

All of that seems to work fine. Can someone give me a quick example of how I might iterate through the nodes in the above xml?

thanks

Information is not Knowledge, Knowledge is not Wisdom, Wisdom is not Truth, Truth is not Beauty, Beauty is not Love, Love is not Music, Music is the best.
 
This is more of a javascript question, but you'll use a line like

var root = xmlDoc.getElementsByTagName('data');

then some kind of loop like:

for (i = 0; i < root[0].childNodes.length; i++) {
}

be sure to test for an actual node and not just whitespace by using a line like:

if (root[0].childNodes.nodeType != 1) continue;

otherwise Firefox will goof because it considers whitespace to be nodes in themselves.

then acess your data with a line like:

thisnodesvalue = root[0].childNodes.nodeValue

save yourself sometime and realize up front that variable i in this loop will be ((2 x whatyouthinkitshouldbe) + 1) in firefox, and just the other way in IE. You'll need another counter that only gets incremented after testing for the proper nodeType. That way at least your counter will read the same in both browsers, maybe someone else knows an easier way to do it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top