[thelist] Problems traversing XML tree in JavaScript

Paul Waring paul at xk7.net
Tue Aug 2 05:17:01 CDT 2005


I've currently got a relatively simple XML file that is structured like
so:

<?xml version="1.0" ?>
<sites>
	<site id="10">Site name 1</site>
	<site id="11">Site name 2</site>
	[several more lines like the above]
</sites>

I've managed to get JavaScript to read in the whole file, using some
code that I found on Site Point, and I'm getting the document using:

response = req.responseXML.documentElement;

where req is an instance of XMLHttpRequest() (or ActiveXObject in IE,
but I'm testing in Firefox first just to see if I can get *something* to
work). This is only set after I've checked that req.readyState is equal
to 4 and the response code is 200 (i.e. everything's gone ok with
regards to reading the document in). I then have the following two lines
of code, just for testing at the moment:

var sites = response.getElementsByTagName('sites');
var sites2 = response.getElementsByTagName('site');

Based on what I've read the getElementsByTagName() function to do, I
expect the first line to get back an array of one element containing
the first (and in this case only) <sites> tag, which I could then use to
further traverse the tree using sites[0].getElementsByTagName('site').
However, sites is being set to an undefined value and printing its
length gives 0, but sites2 is being set to an array of size 41, which is
correct.

Have I done something obviously wrong? It seems to me like response is
already pointing to what I would expect sites[0] to be, but I want it to
instead hold the root of the XML document otherwise when I add extra
stuff later I won't be able to traverse it properly. I honestly don't
understand why this isn't working as I've just taken the majority of the
code from an article[1] and simply changed the names to reflect my
document structure.

Thanks in advance,

Paul

[1] http://www.sitepoint.com/print/xml-javascript-mozilla

-- 
Rogue Tory
http://www.roguetory.org.uk


More information about the thelist mailing list