Forum Moderators: open

Message Too Old, No Replies

Extracting XML data using getElementsByTagName

         

Wolverine68

4:34 pm on Jun 5, 2009 (gmt 0)

10+ Year Member



I'm trying to extract data from an xml file and then loop through each of the elements and print them out. Here's my xml file:


<?xml version="1.0" encoding="utf-8" ?>
- <musicians>
- <musician>
<name>Bruce Springsteen</name>
<genre>Rock</genre>
<hitsong>Born in the USA</hitsong>
</musician>
- <musician>
<name>B.B. King</name>
<genre>Blues</genre>
<hitsong>The Thrill Is Gone</hitsong>
</musician>
- <musician>
<name>Tim McGraw</name>
<genre>Country</genre>
<hitsong>Live Like You Were Dying</hitsong>
</musician>
- <musician>
<name>Gordon Lightfoot</name>
<genre>Folk</genre>
<hitsong>Carefree Highway</hitsong>
</musician>
- <musician>
<name>Glenn Miller</name>
<genre>Big Band</genre>
<hitsong>In The Mood</hitsong>
</musician>
</musicians>

Here's the html file:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<head>
<title>Intro to AJAX--create and send an XMLHttpRequest object to the server</title>

<script type="text/javascript" language="javascript">
<!--The object detection code -->
var req = false;
// Is there support for native XHR object?: IE7+, Firefox, Safari, Opera
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
//create an XMLHttpRequest object
}

else if (window.ActiveXObject)
//check for Version 6
{
req = new ActiveXObject('MSXML2.XMLHTTP.6.0');
//create an ActiveX XMLHTTP component
}
if (!req)
{
req = new ActiveXObject('MSXML2.XMLHTTP');
//fallback to version 3
}

function goXml()
{

if (req)
{
//Request data to be retrieved from the server

req.onreadystatechange = function() {

if(req.readyState == 4 & req.status == 200) {
x= req.responseXML.getElementsByTagName('musician');

for (i=0;i<x.length;i++) {
document.write(x[i].childNodes[0,2].nodeValue);
document.write("<br />");
}
}

else {
document.write("Retrieving message. One moment...");
}
}

}
req.open("GET", "MusicianList.xml", true);
req.send(null);
}

//-->
</script>
</head>

<form>
Click the button to show the list: <input type="button" value="Display the List" onClick="goXml()">
</form>

</body>
</html>

Here's the result when the program is run:

Retrieving message. One moment...null
null
null
null
null

Anyone have any suggestions?

daveVk

1:22 am on Jun 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Assume this expression in error

x[i].childNodes[0,2].nodeValue

try

x[i].getElementsByTagName('hitsong')[0].nodeValue