473,385 Members | 1,570 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,385 software developers and data experts.

problem with reading XML-Document in Firefox

31
Re XML, Javascript, IE, Firefox
Hi,
I have a very simple & small XML file (only 7 variables). The code works for IE, but not for Firefox. I've search around and found lots of alternatives, but all different and mostly way above my competance level to understand (ieg Ajax;-(). Could someone give me some guidance please. - thanks

Expand|Select|Wrap|Line Numbers
  1.    var xmlDoc;
  2. // Code for IE
  3. if (window.ActiveXObject)
  4. {
  5.     document.write("IE detected<br>");
  6.     xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  7.     xmlDoc.async=false;
  8.     xmlDoc.load("readings.xml");
  9.     var save = xmlDoc.getElementsByTagName("save")[0].childNodes[0].nodeValue;
  10. // ... followed by a similar line for the 6 other input variables.
  11. }
  12. // Code for Mozilla, Firefox, Opera, etc.
  13. else if (document.implementation && document.implementation.createDocument)
  14. {
  15.     document.write("Firefox detected<br>");
  16.     xmlDoc=document.implementation.createDocument("","",null);
  17.     xmlDoc.load("readings.xml");
  18.     xmlDoc.onload=readxmldata;  // gives error that onload is not legal!!
  19.     var save = xmlDoc.getElementsByTagName("save")[0].childNodes[0].nodeValue;
  20. // ... followed by a similar line for the 6 other input variables
  21. }
  22. else
  23. {
  24.     alert('Your browser cannot handle this script');   //For TESTING ONLY
  25. }
  26.  
  27. // for testing:
  28. document.write("Save  :" + save + "  <br>");
Sep 14 '07 #1
13 2593
pbmods
5,821 Expert 4TB
Heya, Gretsch.

What do you want your code to do? Give an example.
What is your code doing that you don't want it to do? Give an example.
What is your code *not* doing that it is supposed to? Give an example.
Sep 14 '07 #2
Gretsch
31
Thanks,
I want the code to read in the 7 variables from the XML file and allow me to perform calculations with them. When I use IE it all works fine, but when I use Firefox it prints my "Firefox detected" test msg,(so I know it's getting to the right bit of code) but doesnt print the document.write("Save ;" + save + .... line.

Here's a sample bit of my XML file:
Expand|Select|Wrap|Line Numbers
  1. <?xml version="1.0" ?>
  2. <meter_readings>                    
  3. <save>    1234000    </save>            
  4. </meter_readings>
My pasted code above just (should) print the variable to the screen for testing, as the rest of the program is the same for all browser and works OK when tested with IE. It's just reading in the variables with Firefox that I have problems with.
Firefox Javascript console just tells me that "The variable "save" is not defined", from which I deduce one of the earlier lines is wrong .... but which?
Thanks for your help.
Sep 15 '07 #3
gits
5,390 Expert Mod 4TB
hi ...

i assume that the xml-doc is not ready at this point where you try to retrieve the values ... have a look here where you might see that you have to retrieve the values onload of the doc ... have a look at the getmessage() function of the example there.

kind regards
Sep 15 '07 #4
Gretsch
31
Thanks Gits,
When I read your link I thought you had led me to the complete solution; in that my code is in Body, and your suggestion in Head ... but I'm still in trouble.

Your link uses:
document.getElementById("to").innerHTML= xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
and html prints the result using <span id="to">

but I need to perform calcs on the variable, so I'm using (nb. "save" is my 1st variable)
var save = xmlDoc.getElementsByTagName("save")[0].childNodes[0].nodeValue;
but I get the error report "save is not defined.

I include below your links code - with min. needed changes by me.
Could you/someone tell me where I'm going wrong - thanks.

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. var xmlDoc;
  5. function loadXML()
  6. {
  7. // code for IE
  8. if (window.ActiveXObject)
  9.   {
  10.   xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  11.   xmlDoc.async=false;
  12. //  xmlDoc.load("note.xml");     //replaced below by my xml file
  13.     xmlDoc.load("meter_readings.xml");
  14.     getmessage();
  15.   }
  16. // code for Mozilla, Firefox, Opera, etc.
  17. else if (document.implementation &&
  18. document.implementation.createDocument)
  19.   {
  20.   xmlDoc=document.implementation.createDocument("","",null);
  21. //  xmlDoc.load("note.xml");     //replaced below by my xml file
  22.     xmlDoc.load("meter_readings.xml");
  23.   xmlDoc.onload=getmessage;
  24.   }
  25. else
  26.   {
  27.   alert('Your browser cannot handle this script');
  28.   }
  29. }function getmessage()
  30. {
  31. //document.getElementById("to").innerHTML=
  32. //xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
  33. document.getElementById("save").innerHTML=
  34. xmlDoc.getElementsByTagName("save")[0].childNodes[0].nodeValue;
  35. // example line retined above. other variable lines removed,
  36. // my equivalent below 
  37. var save1 = xmlDoc.getElementsByTagName("save")[0].childNodes[0].nodeValue;
  38. }
  39. </script>
  40. </head><body onload="loadXML()">
  41. <h1>W3Schools Internal Note</h1>
  42. <p><b>To:</b> <span id="to"></span><br />
  43. // other variable lines removed
  44. // my equivant below
  45. <script type="text/javascript">
  46. document.write("Save1  :"  + save1 + "<br>");
  47. </script>
  48. </p>
  49. </body>
  50. </html> 
Sep 16 '07 #5
acoder
16,027 Expert Mod 8TB
You're accessing save1 before it is defined (it's defined after page load).

Don't use document.write - you can't use it after page load. You could use innerHTML of a div or span to display. Put this inside getmessage().
Sep 16 '07 #6
Gretsch
31
Thanks acoder for your guidance,

Perhaps you/someone would help me with the overall concept of where to put each bit of code, because I seem to be going round & round in circles trying things.

What my code needs to do is:
a) open an XML file and read some variables in.
b) perform some simple maths on the variables
c) Display the basic page .. so visitors can start reading something
d) Display the results of b) above top-left of the window (without any movement of existing text).

Please feel free to comment/overrule below:

I assume:
a) should be in the head - called 'onload'
b) should be in the head - called from above
c) is in body
d) is in body - and will need InnerHTML and <span>'s
Sep 17 '07 #7
acoder
16,027 Expert Mod 8TB
What my code needs to do is:
a) open an XML file and read some variables in.
b) perform some simple maths on the variables
c) Display the basic page .. so visitors can start reading something
d) Display the results of b) above top-left of the window (without any movement of existing text).

Please feel free to comment/overrule below:

I assume:
a) should be in the head - called 'onload'
b) should be in the head - called from above
c) is in body
d) is in body - and will need InnerHTML and <span>'s
a) ok
b) ok
c) ok
d) call from a), but after b).

The basic idea is that you can't access something until it is available. Once the XML file is completely loaded, the data becomes available. So the calculations must be made afterwards and likewise for the results. If you haven't made the calculations, you can't display the result, so this must come after b).
Sep 18 '07 #8
Gretsch
31
Hi,
I've taken all your advice above (I think/hope ;-) and got it all working for both IE and Firefox. - thanks
I then inserted an extra bit of code to update the figues every second, but now I get the error that my variable is "not defined".

I've added (for testing) 2 alerts to test where I'm losing the variable
The alert "TEST 1" (below) displays the variable OK,
but only a couple of lines later the alert "TEST 2" fails because the variable is not defined.

I'm tearing my hair out trying to see where the error is, can someone save my sanity (& hair) for me ;-) Thanks



[HTML]<html>
<head>
<script type="text/javascript">
var xmlDoc;
function loadXML()
{
// code for IE
if (window.ActiveXObject)
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("meter_readings.xml");
getmessage();
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xmlDoc=document.implementation.createDocument(""," ",null);
xmlDoc.load("meter_readings.xml");
xmlDoc.onload=getmessage;
}
else
{
alert('Your browser cannot handle this script');
}

alert(dated); // Just for testing TEST 2

update_meter();

}
function getmessage()
{
var save = xmlDoc.getElementsByTagName("save")[0].childNodes[0].nodeValue;
var kwh = xmlDoc.getElementsByTagName("kwh")[0].childNodes[0].nodeValue;
var co2 = xmlDoc.getElementsByTagName("co2")[0].childNodes[0].nodeValue;
var daily_save = xmlDoc.getElementsByTagName("daily_save")[0].childNodes[0].nodeValue;
var daily_kwh = xmlDoc.getElementsByTagName("daily_kwh")[0].childNodes[0].nodeValue;
var daily_co2 = xmlDoc.getElementsByTagName("daily_co2")[0].childNodes[0].nodeValue;
var dated = xmlDoc.getElementsByTagName("dated")[0].childNodes[0].nodeValue;

alert(dated); // Just for testing TEST 1
}

// Functions to reformat the digits
// decimal digits truncation
Number.prototype.truncate = function(n) { return Math.round(this * Math.pow(10, n)) / Math.pow(10, n); }

// String reverse
String.prototype.reverse = function() { return this.split('').reverse().join(''); }

// integer thousand separators
Number.prototype.group = function()
{
var s = parseInt(this).toString().reverse(), r = '';
for (var i = 0; i < s.length; i++)
r += (i > 0 && i % 3 == 0 ? ',' : '') + s.charAt(i);
return r.reverse();
}

// format a number with n decimal digits and thousands separator
Number.prototype.format3s = function(n)
{
// truncate and the fractional part
var f = this.truncate(n);
// grouped integer part + dot + fractional part
return this.group();
}

// Timer to update the meter digits every x secs
function timerfunction()
{
start++;
document.getElementById("span_testing") .innerHTML = start; // for testing
alert(start)
alert(dated)
var current_date = new Date();
// Calc days elapsed between 'dated' & 'current_date
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = current_date.getTime()
var date2_ms = Date.parse(dated);
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days
var days_elapsed = (difference_ms/ONE_DAY)

var current_kwh = ((daily_kwh * days_elapsed) + (kwh * 1));
document.getElementById("span_kwh") .innerHTML = current_kwh.format3s(0);

var current_co2 = ((daily_co2 * days_elapsed) + (co2 * 1));
document.getElementById("span_co2") .innerHTML = current_co2.format3s(0);

var current_save = ((daily_save * days_elapsed) + (save * 1));
document.getElementById("span_save") .innerHTML = current_save.format3s(0);
}

function update_meter()
{
start = 0; //start number
window.setInterval("timerfunction()", 1000); // 1000 = 1 second
}

</script>
</head>
<body onload="loadXML()">

<table border="0" width="208" cellspacing="0" cellpadding="0" background="images/meter_back.gif">
<tr>
<td align="right" height="25" width="65">
<td align="right" height="25" width="130">
<td align="right" height="25">
<tr>
<td align="right" width="65" height="25"><font color="#FFFFFF" face="Arial"><strong>
<em style="font-style: normal">kWh:</em></strong></font></td>
<td align="right" width="130" height="25">
<font face="Arial" color="#FFFFFF" style="font-size: 16pt">
<span id="span_kwh">?,???,???</span></font><font face="Arial" style="font-size: 16pt">
</font>
<td align="right" height="25">
<tr>
<td align="right" width="65" height="25"><font color="#00FF00" face="Arial"><strong>
<em style="font-style: normal">CO<sub>2</sub> kg:</em></strong></font></td>
<td align="right" width="130" height="25">
<font face="Arial" color="#00FF00" style="font-size: 16pt">
<span id="span_co2">?,???,???</span></font><font face="Arial" style="font-size: 16pt">
</font>
<td align="right" height="25">
<tr>
<td align="right" width="65" height="25">
<font color="#00FFFF" style="font-size: 16pt" face="Arial">£:</font></td>
<td valign="bottom" align="right" width="130" height="25">
<font face="Arial" color="#00FFFF" style="font-size: 16pt">
<span id="span_save">?,???,???</span></font><font face="Arial" style="font-size: 16pt">
</font>
<td valign="top" align="right" height="25">
<tr>
<td align="right" height="25" width="65"></td>
<td valign="top" align="right" height="25" width="130">
<td valign="top" align="right" height="25">
</tr>
</table>
<p>

For testing: <span id="span_testing">xxxxx</span>

</body>

</html>[/HTML]
Sep 27 '07 #9
acoder
16,027 Expert Mod 8TB
Where do you get the variable not defined error?

The TEST 2 alert will not work because dated is defined in getmessage().
Sep 27 '07 #10
Gretsch
31
Where do you get the variable not defined error?().
When I run the program in both IE & Firefox (ie before I put in the test alerts.

The TEST 2 alert will not work because dated is defined in getmessage().
..but getmessage runs before TEST 2.
ie I inserted the TEST 1 alert in getmessage (to confirm it was running & retreiving the variables, which it is)
.. then inserted TEST 2 alert ... by which time it is lost.

Once defined, a variable's scope is global isn't it?
Sep 27 '07 #11
acoder
16,027 Expert Mod 8TB
Once defined, a variable's scope is global isn't it?
No it's not. See this article.
Sep 28 '07 #12
Gretsch
31
No it's not. See this article.
That explains a lot of the issues I've been having.
An excellent forum.
Thanks VERY much for your time & help :-)
Sep 28 '07 #13
acoder
16,027 Expert Mod 8TB
Glad I could be of help and thank pbmods for that article.

Post again if you have any more questions.
Sep 28 '07 #14

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

Similar topics

5
by: Nick Shaw | last post by:
Hi, I'm trying to put my resume on my website, and I want to do it using XML and XSL. If I don't include the schema in the mix, the xml displays without a problem. When I add the schema...
9
by: Xarky | last post by:
Hi, I am writing an XML file in the following way. Now I need to read again that file to retrieve data such as Name and Age. Can someone help me out. Thanks in Advance ...
0
by: julio villalba | last post by:
Hi everyone im trying to generate an xml by reading a blank xml, with only the field description on it, and changing the values on that xml and saving it. im doing this by reading the xml with a...
3
by: Paul Bromley | last post by:
I have an application that needs to utilise an XML file produced by an external application. However I am having problems getting this into a Dataset using...
0
by: blabla120 | last post by:
Hi NG, I want to read a xml-file from an asp-page: // Kategorien aus xml laden string pathKategorien = Server.MapPath("./conf/kategorien.xml"); FileStream fs = new FileStream(pathKategorien,...
2
by: Barry | last post by:
Hi I have created the following class for reading XML Message from UPS, i use XMLSerializer to read the xml file , there is a minor problem , Response is a single item whereas RatedShipment is...
0
by: zahid | last post by:
hi, i am new o XML , i have a problem reading XML in ASP .the problem is the XML file has a <!DOCTYPE refering to external .dtd file when i remove this tag it works fine but when i add it it gives me...
1
by: Pathik | last post by:
Hi All, I have to get the values of "reading" and "value" elements of context Person/Category/Group/ser.These values must be on condition based,means I have to get the values of "reading" and...
5
blazedaces
by: blazedaces | last post by:
Ok, so you know my problem, java is running out of memory reading with SAX, the event-based xml parser intended more-so than DOM for extremely large files. I'll try to explain what I've been doing...
10
by: oktayarslan | last post by:
Hi all; I have a problem when inserting an element to a vector. All I want is reading some data from a file and putting them into a vector. But the program is crashing after pushing a data which...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.