Firefox 4k XML node limit

Did you know that Firefox has a 4096 character limit for XML nodes? I didn't until today, and it took me quite a while to track it down! Here is the scenario: You make an AJAX request for some data, you then navigate the DOM of the returned XML data and extract the data you're after. Something like:

function ajaxResponseHander(xml)
    var dataNode = xml.firstChild;
    var data = dataNode.firstChild.nodeValue;
    // now do something with the extracted data...

This works fine in IE, Safari, and Opera. It'll even work fine in Firefox. That is until your data exceeds 4k. At that point you'll only get the first 4096 characters. This is because Firefox splits any node that exceeds 4k into multiple nodes. Say, for example, you have a node with 6316 characters then you will end up having a node with the following properties:

dataNode.childNodes.length == 2;
dataNode.childNodes[0].length == 4096;
dataNode.childNodes[1].length == 2220;

Fortunately Firefox provides the textContent attribute, so we can just use:

var data = dataNode.textContent; // data.length == 6316

Although because IE doesn't support the textContent attribute, we're better off writing a function:

function getNodeText(xmlNode)
    if(!xmlNode) return '';
    if(typeof(xmlNode.textContent) != "undefined") return xmlNode.textContent;
    return xmlNode.firstChild.nodeValue;

I hope I've saved someone some pain!

Posted on 18 Jun 2008
If you enjoyed reading this post you might want to follow @coderholic on twitter or browse though the full blog archive.