XML parsing with firefox

For a project that I was doing, I need to parse a XML data combined with the XSL using JavaScript and grab the latest attribute name…and it’s sucks..BIG TIME! For some reason, it only works with Internet Explorer and not Firefox.

After I did some research, I found out that Internet Explorer and Firefox has a different way to handle this XML document. So the way the nodes are called is also different in both Internet Explorer and Firefox, thats why it shows errors when I tried to parse the XML document.

For example, if the xml data looks like this:

  1. <root>
  2.    <broadcast state="archive" name="testName">
  3.       <description>desc here</description>
  4.    </broadcast>
  5.    <broadcast state="archive2" name="testName2">
  6.       <description>desc here 2</description>
  7.    </broadcast>
  8. </root>

The JavaScript code to load this XML data will be:

  1. var xmlDoc;
  2. var xmlObj;
  3. function loadXML()
  4. {
  5. // code for IE
  6. if (window.ActiveXObject)
  7.   {
  8.           xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  9.           xmlDoc.async=false;
  10.           xmlDoc.load("data.xml");
  11.           xmlObj=xmlDoc.documentElement;
  12.           getmessage();
  13.   }
  14. // code for Mozilla, Firefox, Opera, etc.
  15. else if (document.implementation &&
  16. document.implementation.createDocument)
  17.   {
  18.           xmlDoc= document.implementation.createDocument("","",null);
  19.           xmlDoc.load("data.xml");
  20.           xmlDoc.onload=getmessageMozilla;
  21.   }
  22. else
  23.   {
  24.         alert(‘Your browser cannot handle this script’);
  25.   }
  26. }

This script will load the XML data for both the Internet Explorer and Firefox. But the way the nodes are called is different! Thats why I used different function to called the nodes (getMessage & getMessageMozilla).

Supposedly, we need to retrieve the value of the 1st attribute on the 1st node of the XML data above which is “name”, it should return “testName”, then the code will be:

  1. function getmessage()
  2. {
  3.         var name= xmlObj.childNodes(0).getAttribute("name");
  4.         alert(name);
  5. }
  6.  
  7. function getmessageMozilla()
  8. {
  9.         var name= xmlDoc.childNodes[0].getElementsByTagName("broadcast")[0].getAttribute("name");
  10.         alert(name);
  11. }

And…it should works :)