473,569 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with reading XML-Document in Firefox

31 New Member
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 2606
pbmods
5,821 Recognized Expert Expert
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 New Member
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 Recognized Expert Moderator Expert
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 New Member
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.getEle mentById("to"). innerHTML= xmlDoc.getEleme ntsByTagName("t o")[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.getEleme ntsByTagName("s ave")[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 Recognized Expert Moderator MVP
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 New Member
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 Recognized Expert Moderator MVP
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 New Member
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.ActiveX Object)
{
xmlDoc=new ActiveXObject(" Microsoft.XMLDO M");
xmlDoc.async=fa lse;
xmlDoc.load("me ter_readings.xm l");
getmessage();
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.imple mentation && document.implem entation.create Document)
{
xmlDoc=document .implementation .createDocument ("","",null) ;
xmlDoc.load("me ter_readings.xm l");
xmlDoc.onload=g etmessage;
}
else
{
alert('Your browser cannot handle this script');
}

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

update_meter();

}
function getmessage()
{
var save = xmlDoc.getEleme ntsByTagName("s ave")[0].childNodes[0].nodeValue;
var kwh = xmlDoc.getEleme ntsByTagName("k wh")[0].childNodes[0].nodeValue;
var co2 = xmlDoc.getEleme ntsByTagName("c o2")[0].childNodes[0].nodeValue;
var daily_save = xmlDoc.getEleme ntsByTagName("d aily_save")[0].childNodes[0].nodeValue;
var daily_kwh = xmlDoc.getEleme ntsByTagName("d aily_kwh")[0].childNodes[0].nodeValue;
var daily_co2 = xmlDoc.getEleme ntsByTagName("d aily_co2")[0].childNodes[0].nodeValue;
var dated = xmlDoc.getEleme ntsByTagName("d ated")[0].childNodes[0].nodeValue;

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

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

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

// integer thousand separators
Number.prototyp e.group = function()
{
var s = parseInt(this). toString().reve rse(), 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.prototyp e.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.getEle mentById("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.ge tTime()
var date2_ms = Date.parse(date d);
// 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.getEle mentById("span_ kwh") .innerHTML = current_kwh.for mat3s(0);

var current_co2 = ((daily_co2 * days_elapsed) + (co2 * 1));
document.getEle mentById("span_ co2") .innerHTML = current_co2.for mat3s(0);

var current_save = ((daily_save * days_elapsed) + (save * 1));
document.getEle mentById("span_ save") .innerHTML = current_save.fo rmat3s(0);
}

function update_meter()
{
start = 0; //start number
window.setInter val("timerfunct ion()", 1000); // 1000 = 1 second
}

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

<table border="0" width="208" cellspacing="0" cellpadding="0" background="ima ges/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"><fo nt color="#FFFFFF" face="Arial"><s trong>
<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"><fo nt color="#00FF00" face="Arial"><s trong>
<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_testin g">xxxxx</span>

</body>

</html>[/HTML]
Sep 27 '07 #9
acoder
16,027 Recognized Expert Moderator MVP
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

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

Similar topics

5
1586
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 location to the xml, however, it doesn't seem to be displaying the html tags. It just puts all the information on the screen in one big block, almost...
9
1987
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 /*********************************/ static void writeXML() {
0
854
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 dataset and then with a dataview and a datarowview i get into the fields and change its values, ok till here. When i open the new xml file the order...
3
1281
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 dsOrganisation.ReadXml("c:\testmodify.xml"). I am getting an error that states:- The same table (Address) cannot be the child table in tow nested relations. Address seems to be an...
0
1309
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, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader sr = new StreamReader( fs );
2
1243
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 an array, but when reading it shows on one item for RatedShipment , where as there are seven items , how do i correct this problem, itried to add ()...
0
984
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 an error. if u have any idea why its happening ? i will appericiate your help. the code is : Set xml =...
1
1803
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 "value" if entity="abc" and value="1" , and entity= "def" and value="2" at the Person/Category/Group/series/Key. My xml source file is as follows.
5
14975
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 and why I have to do it. Hopefully someone has a suggestion... Alright, so I'm using a gps-simulation program that outputs gps data, like...
10
2187
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 has string value. I really do not understand why push_back() function is trying to remove previously inserted data. Thanks for any help
0
7614
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...
0
7924
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. ...
1
7676
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...
1
5513
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5219
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...
0
3653
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...
1
2114
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
1
1221
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
938
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...

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.