How to access a specific element in the an XML file using the JavaScript DOM

S

SM

Hello,
Im trying to access elements in my XML file using the JavaScript DOM
but i'm not sure how. I use AJAX to access the XML and then use the
responseXML property to access the XML file data.
I want to extract all the tracks from a specific CD.
Right now, im using an array to stock all the data but its just a
question of time before everything blows up because of the size of the
array. Thats why im want to use an XML file (later i will try to learn
mysql or a similar database)

Heres how my html looks like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<script type="text/javascript" src="js/ajax.js"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<title>Untitled Document</title>
</head>

<body>
<div id="content">
<ul>
<li><a href="javascript: void showCD()">CD 1</a></li>
<li><a href="javascript: void showCD()">CD 2</a></li>
<li>Como yo te amo</li>
<li>Se nos rompío el amor (Con Malú)</li>
<li>Me ha dicho la luna (Con Chayanne)</li>
</ul>

<div id='tracks'></div>
</div>
</body>

</html>


And my AJAX file, notice that in the function getCDInfo(), i'm using a
JavaScript array instead of the XML file. That's coz i dont know how
to access a specific CD in the XML list. Also the function
getCDInfoUsingXML() is the one i need help with

// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();

/
*--------------------------------------------------------------------------------
*/
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp;

// this should work for all browsers except IE
try {xmlHttp = new XMLHttpRequest();}
catch(e)
{
// this should work for IE
try {xmlHttp = new ActiveXObject('MSXML2.XMLHTTP');}
catch(e)
{
// this should work for older IE
try {xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');}
catch(e) {}
}
}

// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}

/
*--------------------------------------------------------------------------------
*/
function showCD()
{
// only continue if xmlHttp isn't void
if (xmlHttp)
{
// try to connect to the server
try
{
// initiate reading a file from the server
xmlHttp.open("GET", "discography.xml", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
// display the error in case of failure
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
}
}
}

/
*--------------------------------------------------------------------------------
*/
// function called everytime the state of the HTTP request changes
function handleRequestStateChange()
{
// when readyState is 4, we are ready to read the server response
if (xmlHttp.readyState == 4)
{
// continue only if HTTP status is "OK"
if (xmlHttp.status == 200)
{
try
{
// do something with the response from the server
getCDInfo();
}
catch(e)
{
// display error message
alert("Error reading the response: " + e.toString());
}
}
else
{
// display status message
alert("There was a problem retrieving the data:\n" +
xmlHttp.statusText);
}
}
}

/
*--------------------------------------------------------------------------------
*/
function getCDInfo() {
var myDiv = document.getElementById("tracks");
myDiv.innerHTML = '';
var cdTrack = new Array();
cdTrack[0] = 'Forever';
cdTrack[1] = 'Night Sky';
cdTrack[2] = 'Ignacio';

//create the Title of the CD
oH1 = document.createElement('h1');
oH1Text = document.createTextNode('Eternity');
oH1.appendChild(oH1Text);

/*-------------- Create the list of tracks --------------*/
oUL = document.createElement('ul');

for(i=0; i < cdTrack.length; i++) {
oTrack = document.createElement('li');
oTrackTitle = document.createTextNode(cdTrack);
oTrack.appendChild(oTrackTitle);

oUL.appendChild(oTrack);
}

//get the CD Cover
var url = "images/discography/250px/eternity.jpg";
oCDCover = document.createElement('img');
oCDCover.setAttribute("src", url);

myDiv.appendChild(oH1);
myDiv.appendChild(oUL);
myDiv.appendChild(oCDCover)
}

/
*--------------------------------------------------------------------------------
*/
// handles the response received from the server
function getCDInfoUsingXML()
{
// read the message from the server
var xmlResponse = xmlHttp.responseXML;

//catching potential errors with IE, Opera
if(!xmlResponse || !xmlResponse.documentElement)
throw('Invalid XML structure:\n' + xmlHttp.responseText);

//catching potential errors with Firefox
var rootNodeName = xmlResponse.documentElement.nodeName;
if(rootNodeName == 'parseerror')
throw('Invalid XML structure:\n' + xmlHttp.responseText);

// obtain the XML's root element
xmlRoot = xmlResponse.documentElement;

...

//iterate through the arrays and create an HTML structure
for (var i=0; i<arrayCD.length; i++)
{
...
}

...
}

And heres my XML file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<discography>
<cd id='1'>
<title>Vision</title>
<description>...</description>
<track>
<title>track1</title>
<title>track2</title>
<title>track3</title>
</track>
</cd>
<cd id='2'>
<title>Eternity</title>
<description>...</description>
<track>
<title>Forever</title>
<title>Night Sky</title>
<title>Ignacio</title>
</track>
</cd>
</discography>


In my HTML file im calling the AJAX function like this:
<li><a href="javascript: void showCD()">CD 1</a></li>

Also, it would be better if a pass the CD as a parameter.

I need help coz i've been searching like crazy for weeks on how to
achieve this with no success

Thanks
Marco
 
C

Cah Sableng

// handles the response received from the server
function getCDInfoUsingXML()
{
// read the message from the server
var xmlResponse = xmlHttp.responseXML;

//catching potential errors with IE, Opera
if(!xmlResponse || !xmlResponse.documentElement)
throw('Invalid XML structure:\n' + xmlHttp.responseText);

//catching potential errors with Firefox
var rootNodeName = xmlResponse.documentElement.nodeName;
if(rootNodeName == 'parseerror')
throw('Invalid XML structure:\n' + xmlHttp.responseText);

// obtain the XML's root element
xmlRoot = xmlResponse.documentElement;

// get all elements with tag 'cd'
cdElms = xmlRoot.getElementsByTagName('cd');
for (i=0;i<cdElms.length;i++)
{
for (j=0;j<cdElms.item(i).childNodes.length;j++)
{
// only elements, please
if (cdElms.item(i).childNodes[j].nodeType===1)
{
switch (cdElms.item(i).childNodes[j].tagName)
{
case 'title':
alert('title: '+cdElms.item(i).childNodes[j].childNodes[0].nodeValue);
break;
case 'description':
alert('desc: '+cdElms.item(i).childNodes[j].childNodes[0].nodeValue);
break;
case 'track':
trackTitle='';
tracks=cdElms.item(i).childNodes[j].getElementsByTagName('title');
for (k=0;k<tracks.length;k++)
trackTitle+='track:' + tracks.item(k).childNodes[0].nodeValue + "\n";
alert(trackTitle);
break;
default:
}
}
}
}

Change alerts in my code to whatever you want.
My code should be optimized and checked whether
cdElms.item(i).childNodes[j] or its child nodes has child nodes or
not.

HTH
 
R

RobG

Hello,
Im trying to access elements in my XML file using the JavaScript DOM
but i'm not sure how.

It's not a javascript DOM. The DOM is created by the browser to some
specification, usually based on a W3C DOM and with various
extensions. Javascript is just the main language used to access an
API provided by the browser to access the DOM (e.g. IE also provides a
VBScript API). But anyhow...

I use AJAX to access the XML and then use the
responseXML property to access the XML file data.
I want to extract all the tracks from a specific CD.

For that you can use the W3C DOM Core stuff:

Right now, im using an array to stock all the data but its just a
question of time before everything blows up because of the size of the
array. Thats why im want to use an XML file (later i will try to learn
mysql or a similar database)

I don't think you need to worry about the size of javascript arrays,
they can get far larger than anything you can reasonably deal with.
The primary reasons for using XML would be to have a common data
format with some other application, or to use XSLT on the client to
format it for presentation.

However, if you are manually processing the XML file you might find it
easier to use JSON.

For example, to use XML you might have something like:

<album>
<title>album title</title>
<artist>someone</artist>
<track>
<id>track01</track>
<name>Song One</name>
<time>6:04</time>
</track>
<track>
<id>track02</track>
<name>Song One</name>
<time>4:023</time>
</track>
...
</album>
<album>
...
</album>

and so on. You could use getElementsByTagName('album') to get all the
albums, then loop through those to get the tracks, etc. Or you could
put the data in as attributes:

<album title="great songs" artist="someone">
<track id="track01" title="Song One" time="6:04"/>
<track id="track02" title="Song Two" time="5:23"/>
...
</album>
<album ...>
...
</album>

or whatever. But the above is very close to JSON:

var data = { album00: {
title: "album title",
artist: "someone",
track01: {
name: "Song One",
time: "6:04"
},
track02: {
name: "Song Two",
time: "5:23"
}
},
album01: {
...
}
};

Then eval the returned JSON text and there's your object to start
putting data into the table (say using for..in to loop over the
properties).

As for using AJAX, there are a number of libraries around for making
that easier, e.g. jQuery:

<URL: http://docs.jquery.com/Ajax >


Over to you...
 
S

SM

It's not a javascript DOM. The DOM is created by the browser to some
specification, usually based on a W3C DOM and with various
extensions. Javascript is just the main language used to access an
API provided by the browser to access the DOM (e.g. IE also provides a
VBScript API). But anyhow...


For that you can use the W3C DOM Core stuff:



I don't think you need to worry about the size of javascript arrays,
they can get far larger than anything you can reasonably deal with.
The primary reasons for using XML would be to have a common data
format with some other application, or to use XSLT on the client to
format it for presentation.

However, if you are manually processing the XML file you might find it
easier to use JSON.

For example, to use XML you might have something like:

<album>
<title>album title</title>
<artist>someone</artist>
<track>
<id>track01</track>
<name>Song One</name>
<time>6:04</time>
</track>
<track>
<id>track02</track>
<name>Song One</name>
<time>4:023</time>
</track>
...
</album>
<album>
...
</album>

and so on. You could use getElementsByTagName('album') to get all the
albums, then loop through those to get the tracks, etc. Or you could
put the data in as attributes:

<album title="great songs" artist="someone">
<track id="track01" title="Song One" time="6:04"/>
<track id="track02" title="Song Two" time="5:23"/>
...
</album>
<album ...>
...
</album>

or whatever. But the above is very close to JSON:

var data = { album00: {
title: "album title",
artist: "someone",
track01: {
name: "Song One",
time: "6:04"
},
track02: {
name: "Song Two",
time: "5:23"
}
},
album01: {
...
}
};

Then eval the returned JSON text and there's your object to start
putting data into the table (say using for..in to loop over the
properties).

As for using AJAX, there are a number of libraries around for making
that easier, e.g. jQuery:

<URL:http://docs.jquery.com/Ajax>

Over to you...

thanks for both the tips guys. I greatly appreciated

Marco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top