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:
-
<root>
-
<broadcast state="archive" name="testName">
-
<description>desc here</description>
-
</broadcast>
-
<broadcast state="archive2" name="testName2">
-
<description>desc here 2</description>
-
</broadcast>
-
</root>
The JavaScript code to load this XML data will be:
-
var xmlDoc;
-
var xmlObj;
-
function loadXML()
-
{
-
// code for IE
-
if (window.ActiveXObject)
-
{
-
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
-
xmlDoc.async=false;
-
xmlDoc.load("data.xml");
-
xmlObj=xmlDoc.documentElement;
-
getmessage();
-
}
-
// code for Mozilla, Firefox, Opera, etc.
-
else if (document.implementation &&
-
document.implementation.createDocument)
-
{
-
xmlDoc= document.implementation.createDocument("","",null);
-
xmlDoc.load("data.xml");
-
xmlDoc.onload=getmessageMozilla;
-
}
-
else
-
{
-
alert(‘Your browser cannot handle this script’);
-
}
-
}
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:
-
function getmessage()
-
{
-
var name= xmlObj.childNodes(0).getAttribute("name");
-
alert(name);
-
}
-
-
function getmessageMozilla()
-
{
-
var name= xmlDoc.childNodes[0].getElementsByTagName("broadcast")[0].getAttribute("name");
-
alert(name);
-
}
And…it should works ![]()
Leave a Reply