473,606 Members | 3,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I extract data from XML

15 New Member
Hi,

I quite new to Javascript and XML. Here a is snippet of my XML file.

Expand|Select|Wrap|Line Numbers
  1. <xml>
  2. <cd>
  3.     <rock>
  4.         <item id='1'>
  5.             <name>Bon Jovi</name>
  6.             <price>$10</price>
  7.             <description>abc</description>
  8.         </item>
  9.         <item id='2'>
  10.             <name>U2</name>
  11.             <price>$11</price>
  12.             <description>abc</description>
  13.         </item>
  14.         <item id='3'>
  15.             <name>Linkin Park</name>
  16.             <price>$12</price>
  17.             <description>abc</description>
  18.         </item>
  19.     </rock>
  20.     <pop>
  21.         <item id='1'>
  22.             <name>Nelly</name>
  23.             <price>$5</price>
  24.             <description>abc</description>
  25.         </item>
  26.         <item id='2'>
  27.             <name>Justin</name>
  28.             <price>$5</price>
  29.             <description>abc</description>
  30.         </item>
  31.     </pop>
  32. </cd>
  33. </xml>
  34.  
I am working with javascript.
Basically I have 2 problems.
1. How do I just get the 'name' from all the items in <rock> tags?
2. How do I get the the 'name' from a specific position node? For example, I want to get the name of the artist in <rock> from node 1 onwards. -> Expected output: U2, Linkin Park.

Thanks so much in advance.

Regards,
Gordon
Oct 24 '07 #1
10 11992
dmjpro
2,476 Top Contributor
actually where this file exists??

debasis
Oct 24 '07 #2
acoder
16,027 Recognized Expert Moderator MVP
Gordon, welcome to TSDN!

Check out this link. You'll want to make use of the document.getEle mentsByTagName( ) method.
Oct 24 '07 #3
spoken
15 New Member
Hi acoder,

I've seen that link. However, I just want to get the 'name' for the items in <rock>.
I have tried
xmldoc.getEleme ntsByTagName('i tems')
but that gives me all the items, including those in <pop>.

dmjpro,
the file is a seperate xml and the javascript is in my html document. I manage to successfully load the xml already.
Oct 24 '07 #4
dmjpro
2,476 Top Contributor
Hi acoder,

I've seen that link. However, I just want to get the 'name' for the items in <rock>.
I have tried
xmldoc.getEleme ntsByTagName('i tems')
but that gives me all the items, including those in <pop>.

dmjpro,
the file is a seperate xml and the javascript is in my html document. I manage to successfully load the xml already.

have a look at this ............

Expand|Select|Wrap|Line Numbers
  1. var parent = xmldoc.getElementsByTagName('rock'); //get the parent node
  2. if(parent[0].childNodes.length){
  3. var child1 = parent[0].childNodes[0].getAttribute('name'); //if there is any child nodes
  4. }
  5.  
have the same repetition ...... until the childnodes end.

debasis
Oct 24 '07 #5
spoken
15 New Member
have a look at this ............

Expand|Select|Wrap|Line Numbers
  1. var parent = xmldoc.getElementsByTagName('rock'); //get the parent node
  2. if(parent[0].childNodes.length){
  3. var child1 = parent[0].childNodes[0].getAttribute('name'); //if there is any child nodes
  4. }
  5.  
have the same repetition ...... until the childnodes end.

debasis

Hi debasis,

Thanks for your reply.
I've tried your code and I can't get any output. This is wat I wrote.

Expand|Select|Wrap|Line Numbers
  1. var parent = xmldoc.getElementsByTagName('rock'); //get the parent node
  2. alert(parent);
  3. if(parent[0].childNodes.length){
  4.     var child1 = parent[0].childNodes[0].getAttribute('name'); //if there is any child nodes
  5. }
  6. alert(child1);
I get "HTMLCollection " for the first alert and nothing comes out for the second, and I'm using the exact XML file as above. I tried to print the whole xml file and it comes out fine.
Oct 24 '07 #6
gits
5,390 Recognized Expert Moderator Expert
hi ...

try the following adaption:

Expand|Select|Wrap|Line Numbers
  1. var p = xmldoc.getElementsByTagName('rock');
  2.  
  3. alert(p);
  4.  
  5. if (p[0].childNodes.length) {
  6.     var child1 = p[0].getElementsByTagName('item')[0];
  7.     var c_name = child1.getAttribute('name'); 
  8. }
  9.  
  10. alert(c_name);
kind regards
Oct 24 '07 #7
spoken
15 New Member
hi ...

try the following adaption:

Expand|Select|Wrap|Line Numbers
  1. var p = xmldoc.getElementsByTagName('rock');
  2.  
  3. alert(p);
  4.  
  5. if (p[0].childNodes.length) {
  6.     var child1 = p[0].getElementsByTagName('item')[0];
  7.     var c_name = child1.getAttribute('name'); 
  8. }
  9.  
  10. alert(c_name);
kind regards
Hi Gits,

I tried your code adaption. I can't do child1.getAttri bute('name') because name is not an attribute but a tag. However if I do child1.getAttri bute('id'), I can extract the ID of the item.

But I need to get the value of the <name> tag.. :(

This is driving me bonkes.. Thanks for the help...

Regards,
Gordon
Oct 24 '07 #8
acoder
16,027 Recognized Expert Moderator MVP
Hi Gits,

I tried your code adaption. I can't do child1.getAttri bute('name') because name is not an attribute but a tag. However if I do child1.getAttri bute('id'), I can extract the ID of the item.
So, use getElementsByTa gName() again on child1 (which is item) to get the name. That would give you the first name. Use a loop to get all the names of all items.
Oct 24 '07 #9
Ferris
101 New Member
Hi

I just wrote a complete sample code for you~~ It takes me a little long time..

first:save your xml data to file :cd.xml
second:create a new html file, make sure these two files are in the same directory.
then:paste my code into html file.

end:open html file and click the button.


[HTML]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitl ed Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<script language="javas cript">
function readxml(xmlfile )
{
var xmlDoc;
if (window.ActiveX Object){
xmlDoc = new ActiveXObject(" Microsoft.XMLDO M");
xmlDoc.async=fa lse;
}
else if (document.imple mentation && document.implem entation.create Document){
xmlDoc= document.implem entation.create Document("","do c",null);
}
if (typeof xmlDoc!="undefi ned"){
xmlDoc.load(xml file);
}
if (window.ActiveX Object)
{
//for IE
var rock = xmlDoc.getEleme ntsByTagName("r ock")[0];
if (rock != null)
{
var rockitem = rock.getElement sByTagName("ite m");
for (var i=0;i<rockitem. length;i++)
{
var id = rockitem[i].getAttribute(" id");

var name = rockitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
var price = rockitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
var description = rockitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
document.getEle mentById("divro ck").innerHTM L += "item " + i + "<br />";
document.getEle mentById("divro ck").innerHTM L += "name:" + name + "<br />";
document.getEle mentById("divro ck").innerHTM L += "price:" + price + "<br />";
document.getEle mentById("divro ck").innerHTM L += "descriptio n:" + description + "<br />";
}
}
var pop = xmlDoc.getEleme ntsByTagName("p op")[0];
if (pop != null)
{
var popitem = pop.getElements ByTagName("item ");
for (var i=0;i<popitem.l ength;i++)
{
var id = popitem[i].getAttribute(" id");

var name = popitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
var price = popitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
var description = popitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
document.getEle mentById("divpo p").innerHTM L += "item " + i + "<br />";
document.getEle mentById("divpo p").innerHTM L += "name:" + name + "<br />";
document.getEle mentById("divpo p").innerHTM L += "price:" + price + "<br />";
document.getEle mentById("divpo p").innerHTM L += "descriptio n:" + description + "<br />";
}
}
}
else if (typeof xmlDoc!="undefi ned"){
// for firefox
xmlDoc.onload = function (){
var rock = xmlDoc.getEleme ntsByTagName("r ock")[0];
if (rock != null)
{
var rockitem = rock.getElement sByTagName("ite m");
for (var i=0;i<rockitem. length;i++)
{
var id = rockitem[i].getAttribute(" id");

var name = rockitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
var price = rockitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
var description = rockitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
document.getEle mentById("divro ck").innerHTM L += "<strong>it em</strong> " + i + "<br />";
document.getEle mentById("divro ck").innerHTM L += "<strong>na me</strong>:" + name + "<br />";
document.getEle mentById("divro ck").innerHTM L += "<strong>pr ice</strong>:" + price + "<br />";
document.getEle mentById("divro ck").innerHTM L += "<strong>descri ption</strong>:" + description + "<br />";
}
}
var pop = xmlDoc.getEleme ntsByTagName("p op")[0];
if (pop != null)
{
var popitem = pop.getElements ByTagName("item ");
for (var i=0;i<popitem.l ength;i++)
{
var id = popitem[i].getAttribute(" id");

var name = popitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
var price = popitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
var description = popitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
document.getEle mentById("divpo p").innerHTM L += "<strong>it em</strong> " + i + "<br />";
document.getEle mentById("divpo p").innerHTM L += "<strong>na me</strong>:" + name + "<br />";
document.getEle mentById("divpo p").innerHTM L += "<strong>pr ice</strong>:" + price + "<br />";
document.getEle mentById("divpo p").innerHTM L += "<strong>descri ption</strong>:" + description + "<br />";
}
}
};
}
}
</script>
<body>
<h1>read xml file</h1>
rock
<div id="divrock" style="margin-left:10px; "></div>
pop
<div id="divpop" style="margin-left:10px; "></div>
<input type="button" value="read" onclick="readxm l('cd.xml');"/>
</body>
</html>

[/HTML]



by the way:
1:the code can be run in IE and firefox.
2:pay attention to onclick="readxm l('cd.xml'); , the "cd.xml" will tell javascript where your xml file is.if your xml file isn't "cd.xml",ch ange the parameter.
3:pay attention to the following code,I guess these code are what you're looking for:

[HTML]
var rockitem = rock.getElement sByTagName("ite m");
for (var i=0;i<rockitem. length;i++)
{
var id = rockitem[i].getAttribute(" id");
var name =
rockitem[i].getElementsByT agName("name")[0].firstChild.nod eValue;
var price =
rockitem[i].getElementsByT agName("price")[0].firstChild.nod eValue;
var description =
rockitem[i].getElementsByT agName("descrip tion")[0].firstChild.nod eValue;
}
[/HTML]


hope it helps :)
Oct 24 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

1
8624
by: Tim Smith | last post by:
I am looking to extract form element values from html, more generally I have a substring that identifies the beginning of a value and a string that identifies the end of value and I need to extract the substring. My ugly code looks like this: public static String getValue(String data, String begin, String end) { int delimPos = data.indexOf(delim, data.indexOf(begin) +
0
302
by: Brian Hanson | last post by:
Hi, I have an unusual problem that just showed its ugly head at a pretty bad time. I have an asp.net (VB) app that takes data from an Excel sheet and puts it into SQL Server. I get the data out of Excel using OleDB, and suddenly, some of the data was not being extracted from Excel. I use OleDb for the extract into a DataTable and from there an SqlClient.SqlCommand to put it into SQL Server.
7
3128
by: fool | last post by:
Dear group, Extract the integer value present in a given string. So I tried the following: int main(void) { int val; char *data; data = malloc(sizeof *data); if(data)
2
3837
by: missolsr | last post by:
hi, I am using jpcap to capture OLSR topology control (udp) packets. Does anyone know how to extract data (the way ethereal does it) from the olsr packet? There are methods to extract data from udp and IP packets in jpcap but the issue is that olsr packets have their own header-data and since jpcap can not dig that far, I get nonsense as packet data. 1. Am I right to assume that jpcap can not dig to the data part of the packet...
1
2665
by: caine | last post by:
I want to extract web data from a news feed page http://everling.nierchi.net/mmubulletins.php. Just want to extract necessary info between open n closing tags of <title>, <categoryand <link>. Whenever I initiated the extraction, first news title is always "MMU Bulletin Board RSS Feed" with the proper bulletin's link stored, but not the correct news title being stored. Necessary info only appears within <itemand </itemwhich consists...
0
2040
by: napolpie | last post by:
DISCUSSION IN USER nappie writes: Hello, I'm Peter and I'm new in python codying and I'm using parsying to extract data from one meteo Arpege file. This file is long file and it's composed by word and number arguments like this: GRILLE EURAT5 Coin Nord-Ouest : 46.50/ 0.50 Coin Sud-E Hello, I'm Peter and I'm new in python codying and I'm using parsying to extract data from one meteo Arpege file.
3
5710
by: maylee21 | last post by:
hi, anyone can help me figure out how to read data from a text file like this: 10980012907200228082002 and extract the data according to this kind of format: Record type 1 TY-RECORD PIC (1). ID-PARTICIPANT PIC (6).
5
2837
by: =?Utf-8?B?aWxy?= | last post by:
Hi This is probably fairly simple but I am newish at programming and was wondering if someone can give me some advice on handling the following. I have an array with a large number of elements in it. 0-9 are related data, 10-19, 20-29 are related and so on. What is the best way of extracting groups of elements from the array into another array where each element is the related data or to extract say elements 0,1,5 from the first...
7
2103
by: JoeC | last post by:
I am trying to create a windows program that reads binary graphics as a resource. This has nothing to do with win32 but conversion of data with memcpy. graphic::graphic(UINT uiResID, HINSTANCE hinstance){ size = 32; bitData.clear(); void * p = NULL; // point to the data int end; BYTE data;
1
1909
by: sivadhanekula | last post by:
Hi everyone, I have a problem with my Mysql data. I have 2,95,67,456 lines of data which is too much and if I run this in MYSQL front-end it is telling "OUT OF MEMORY". Any way with my collegues system I have got the runned data and I have copied it to my Frontend, now it works. But my problem is if I am extracting particular data from that it is telling "ACCESS VIOLATION" so I have decided to extract only data from the first 1,00,000 lines,...
0
8036
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7978
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,...
0
8461
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8126
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
8317
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
5470
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
3948
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
4010
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1572
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.