xml parsng in Javascript-cross browser issues
If you are building a cross-browser javascript based application which deals with XML parsing then you should remember that its not all about caling getElementByTag() and getElementbyId().
Recently i have finished a personal javascript-xml based application(will post in near future about it) which fetches xml feeds(RSS/Atom) data and display on website via ajax based calls.I have tried my best to target both IE and FF but still many things are left.There are few things which I experienced during development.
1)For IE,XML tags are not different than HTML tags,there it ignores most of the things which should an XML parser should not,for instance well-formedness of an XML document
2)In IE Namespaces are considered part of tag itself,therefore,if you are trying to refer an xml tag with namespace,forInstance <dc:date></dc:date>,all you have to do following:
document.getElementsByTagName("dc:date").firstChild.nodeValue;
while FireFox will not accept it as a single tag,so in order to access such tag,you would have to call getElementsByTagNameNS("path/to/uri",tagName),so above code will be changed to something like:
getElementsByTagNameNS("http://purl.org/dc/elements/1.1/","date").item(0).firstChild.data;
3)in FF getElementsByTagName("tagName").firstChild.nodeValue was not working for me as it was not fetching innerHTML of the node,after an hour search on google,i found the following code by Martin Honnen
function getInnerText (node) {
if (typeof node.textContent != 'undefined') {
return node.textContent;
}
else if (typeof node.innerText != 'undefined') {
return node.innerText;
}
else if (typeof node.text != 'undefined') {
return node.text;
}
else {
switch (node.nodeType) {
case 3:
case 4:
return node.nodeValue;
break;
case 1:
case 11:
var innerText = '';
for (var i = 0; i < node.childNodes.length; i++) {
innerText += getInnerText(node.childNodes
);
}
return innerText;
break;
default:
return '';
}
}
}
In order to use,all you have to use following two lines:
var hq=entry[0].getElementsByTagName("tagName").item(0);
myNode=getInnerText(hq);
Tagged:ajax,javascript,cross browser,FireFox,getElementsByTagName,xml