473,396 Members | 1,599 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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

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[i]);
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

Apr 3 '07 #1
3 3436
On Apr 4, 2:39 am, "SM" <servandomont...@gmail.comwrote:
// 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

Apr 4 '07 #2
On Apr 4, 5:39 am, "SM" <servandomont...@gmail.comwrote:
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:

<URL: http://www.w3.org/TR/DOM-Level-2-Core/core.html >

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

--
Rob

Apr 4 '07 #3
SM
On Apr 3, 11:28 pm, "RobG" <r...@iinet.net.auwrote:
On Apr 4, 5:39 am, "SM" <servandomont...@gmail.comwrote:
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:

<URL:http://www.w3.org/TR/DOM-Level-2-Core/core.html>
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...

--
Rob
thanks for both the tips guys. I greatly appreciated

Marco

Apr 6 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: George Hester | last post by:
I have a css file this is a portion of it: /* trackaccept.css */ div.track { width:400px; height: 100px; } I have this in my ASP page:
1
by: mattrapoport | last post by:
I have a form with an input type='file' element. I click on the Browse button of my file upload element, select a file, and hit open. The file name appears in the textbox portion of the file...
6
by: Jon Davis | last post by:
I recently learned how to do an <OBJECT> alternative to <IFRAME> in current browsers using: <object id="extendedhtml" type="text/html" data="otherpage.html" width="250" height="400"></object> ...
3
by: serge calderara | last post by:
Dear all, How to configure in config file, the fact that all users get access to the root web folder but only some of them to a restricted forlder Any sample ? thnaks for your help regards...
4
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How can I access the client-side filesystem?...
17
by: broughcut | last post by:
Is it possible to fetch a specific div from a source html document using XMLHttpRequest, rather than fetching the entire file? I was going to use Ajax on mouseover but keep the normal link...
22
by: Christopher Nelson | last post by:
I have a little menu system which essentially takes HTML like: <div id='foo'></div> and retrieves foo.shtml from the server and inserts it inside the <div>. But sometimes I'd like foo.shtml...
10
by: Stefan Weber | last post by:
Hi, I'm trying to access the JavaScript code contained in a <scripttag via its "text" attribute. This works well, if the code is embedded in the HTML page. However, when the code is in an...
7
by: JDOMPer | last post by:
Don’t misunderstand me – I use AJAX, but I think there is a far simpler, elegant alternative that just uses Javascript, the DOM and Php ( hence - JDOMP) for data transfers, and is cross-browser...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.