473,765 Members | 1,955 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.dt d">
<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>Untitl ed Document</title>
</head>

<body>
<div id="content">
<ul>
<li><a href="javascrip t: void showCD()">CD 1</a></li>
<li><a href="javascrip t: 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
getCDInfoUsingX ML() is the one i need help with

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

/
*--------------------------------------------------------------------------------
*/
function createXmlHttpRe questObject()
{
// 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.XMLHT TP');}
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("G ET", "discography.xm l", true);
xmlHttp.onready statechange = handleRequestSt ateChange;
xmlHttp.send(nu ll);
}
// 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 handleRequestSt ateChange()
{
// when readyState is 4, we are ready to read the server response
if (xmlHttp.readyS tate == 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.statusT ext);
}
}
}

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

//create the Title of the CD
oH1 = document.create Element('h1');
oH1Text = document.create TextNode('Etern ity');
oH1.appendChild (oH1Text);

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

for(i=0; i < cdTrack.length; i++) {
oTrack = document.create Element('li');
oTrackTitle = document.create TextNode(cdTrac k[i]);
oTrack.appendCh ild(oTrackTitle );

oUL.appendChild (oTrack);
}

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

myDiv.appendChi ld(oH1);
myDiv.appendChi ld(oUL);
myDiv.appendChi ld(oCDCover)
}

/
*--------------------------------------------------------------------------------
*/
// handles the response received from the server
function getCDInfoUsingX ML()
{
// read the message from the server
var xmlResponse = xmlHttp.respons eXML;

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

//catching potential errors with Firefox
var rootNodeName = xmlResponse.doc umentElement.no deName;
if(rootNodeName == 'parseerror')
throw('Invalid XML structure:\n' + xmlHttp.respons eText);

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

...

//iterate through the arrays and create an HTML structure
for (var i=0; i<arrayCD.lengt h; 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>Foreve r</title>
<title>Night Sky</title>
<title>Ignaci o</title>
</track>
</cd>
</discography>
In my HTML file im calling the AJAX function like this:
<li><a href="javascrip t: 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 3470
On Apr 4, 2:39 am, "SM" <servandomont.. .@gmail.comwrot e:
// handles the response received from the server
function getCDInfoUsingX ML()
{
// read the message from the server
var xmlResponse = xmlHttp.respons eXML;

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

//catching potential errors with Firefox
var rootNodeName = xmlResponse.doc umentElement.no deName;
if(rootNodeName == 'parseerror')
throw('Invalid XML structure:\n' + xmlHttp.respons eText);

// obtain the XML's root element
xmlRoot = xmlResponse.doc umentElement;
// get all elements with tag 'cd'
cdElms = xmlRoot.getElem entsByTagName(' cd');
for (i=0;i<cdElms.l ength;i++)
{
for (j=0;j<cdElms.i tem(i).childNod es.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.i tem(i).childNod es[j].getElementsByT agName('title') ;
for (k=0;k<tracks.l ength;k++)
trackTitle+='tr ack:' + tracks.item(k). childNodes[0].nodeValue + "\n";
alert(trackTitl e);
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.comwrot e:
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 getElementsByTa gName('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.comwrot e:
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 getElementsByTa gName('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
15748
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
6645
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 upload element (as expected). When I submit this form everything works perfectly. On the same form I have a hyperlink that simulates clicking on the Browse button of the file upload element. It does this by using the file upload element's name...
6
5266
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> My question is how do I access the document DOM of this object in Javascript? For example, "alert(extendedhtml.innerHTML);" doesn't work and produces an unknown error. I'd like to both read and write to the document's body element's innerHTML...
3
1485
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 serge
4
388
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How can I access the client-side filesystem? ----------------------------------------------------------------------- Security means that by default you can't. In a more restricted enviroment, there are options. For example, using LiveConnect to connect to Java with Netscape, and using the FileSystemObject in IE. Check http://groups.google.com/
17
3549
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 intact, so that if the user does not have javascript they can click the link as normal and this would take them to the new page, but if they have javascript (and ActiveX enabled I guess, in the case of IE) it would just fetch the appropriate div into...
22
2355
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 to look like: <script language='JavaScript'> ...do something AJAX-y </script>
10
2411
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 external file with the "src" attribute, it does not work anymore. Does anybody have an idea if there is any way (be it clean and simple or as a workaround) to access the code of external scripts as well? I read, that if there is something like
7
2024
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 without the need for work arounds. JDOMP works in recent versions of Explorer, Mozilla, Safari and Opera. Please note I will not deal with security issues which are always an issue whenever there is access to a database. You can simply change text on...
0
9398
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9951
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5421
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2805
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.