Jump to content

Extracting XML data using getElementsByTagName


Wolverine68

Recommended Posts

I'm trying to write code that will extract data from an xml file then loop through the elements in the xml file and print them out.

 

Here's the 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>Extract Data from an XML file</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>

 

When it is executed, here's what prints:

 

Retrieving message. One moment...null

null

null

null

null

 

 

Any suggestions?

 

 

Link to comment
Share on other sites

Made some changes to the code but still not working.

 

HTML:

 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<head>
<title>Extract Data from an XML file</title>

<script type="text/javascript" language="javascript">
<!--The object detection code -->
var req = null;
// 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.x.appendChild(childNodes[*]).nodeValue;
         		      }

        }

else {
     req = false;
     }
}

}
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>


 

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>

 

Getting a syntax error for line 43. It doesn't like this piece of code:

 


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

    for (i=0;i<x.length;i++) {
     document.x.appendChild(childNodes[*]).nodeValue;
         		      }

        }


 

I figured I was obtaining the musician tag through my defined x variable then setting up the loop to go through each of the musician tags and attaching the child nodes of the musican tag (name, genre, and hitsong) with appendChild.

 

What am I missing?

Link to comment
Share on other sites

try this

<script type="text/javascript">
function loadXMLDoc(dname) 
{
    var xmlDoc;
    if (window.XMLHttpRequest)
    {
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",dname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
    }
    // IE 5 and IE 6
    else if (ActiveXObject("Microsoft.XMLDOM"))
    {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(dname);
return xmlDoc;
    }
    document.getElementById('output').innerHTML="Error loading document";
    return null;
}
window.onload=function(){
    xmlDoc=loadXMLDoc("music.xml");
    var musicians=xmlDoc.getElementsByTagName('musician');

    for(var i=0;i<musicians.length;i++){
var musicianNames=musicians[i].getElementsByTagName('name');
//will put the names in the names in the div with id output
document.getElementById('output').innerHTML+=musicianNames[0].childNodes[0].nodeValue+"<br />";
    }
}
</script>
<!-- output div-->
<div id="output"></div>

Link to comment
Share on other sites

Thanks for writing out that program. But, I think I'd learn better if I understood where I went wrong with my program and how I could modify it.

 

HTML:

 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<head>
<title>Extract Data from an XML file</title>

<script type="text/javascript" language="javascript">
<!--The object detection code -->
var req = null;
// 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.x.appendChild(childNodes[*]).nodeValue;
         		      }

        }

else {
     req = false;
     }
}

}
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>



 

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>

 

My sticking point seems to be with this piece:

 


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.x.appendChild(childNodes[*]).nodeValue;
         		      }

        }

else {
     req = false;
     }
}

 

Why am I getting a syntax error here?  The variable x sends the request to the server and retrieves the Musicians tag. Then, enters into a loop to get all of the musicians values along with their child nodes, <name>, <genre>, and <hitsong>

Link to comment
Share on other sites

Added some new code but still can't get this to work. Getting syntax error

 

HTML:

 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Extract Data from an XML file</title>

<script type="text/javascript" language="javascript">
<!--The object detection code -->
var req = null;
// 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) {
    var xmlDoc= req.responseXML;
    var musicianInfo = xmlDoc.getElementsByTagName(*);
    for (i=0;i<musicianInfo.length;i++) {
                  document.getElementById('XmlData').innerHTML=musicianInfo[i];
         		      }

        }

else {
     req = false;
     }
}

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


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

<body>
<p>Click the button to show the list: <input type="button" value="Display the List" onClick="goXml()"></p>
<div id="XmlData" style="border:1px solid black;height:40;width:300">
</div>


</body>
</html>

 

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>

 

It doesn't seem to like this piece:

 


if(req.readyState == 4 && req.status == 200) {
    var xmlDoc= req.responseXML;
    var musicianInfo = xmlDoc.getElementsByTagName(*);
    for (i=0;i<musicianInfo.length;i++) {
                  document.getElementById('XmlData').innerHTML=musicianInfo[i];
         		      }

        }

else {
     req = false;
     }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.