disable-output-escaping is not supported in Firefox

CDATA concatenation

or: disable-output-escaping is not supported in Firefox

Recently I was working on generating XML documents to contain arbitrary text. Naturally I wanted to make things easy on myself by wrapping said arbitrary text with CDATA sections. It just so happens that the text in question contains CDATA tags and as everyone knows, CDATA sections can not be nested. After searching around the web and running into "answers" that were pure opinion on what XML is, is for, and should do, I still didn't have the simple answer to a common problem so I wrote it myself and posted it here.

First I tried converting html characters into entities but when I'd apply my XSLT stylesheet to the document I found that all my html entities had been encoded again, so every & became & and that is not at all what I wanted. Then I tried using the disable-output-escaping option but I'm working with Firefox so it didn't have any effect at all. I consulted the great Wikipedia and it hit me with the obvious "all you have to worry about is ]]>" and I immediately realized how lazy I was being. Using the age old trick of escaping literal strings through closing, reopening, and concatenating, I've sidestepped the convoluted solutions posted elsewhere and can just get on with my day. This solution is in JavaScript but it is so simple it could be translated into other languages without a lot of thought.

/**
 * Escapes <code>CDATA</code> sections in text
 *  so that the text may be embedded into a 
 *  <code>CDATA</code> section. This should be run
 *  on any text which may contain the string 
 *  <code>]]></code> since said string will effectively
 *  end the <code>CDATA</code> section prematurely.
 * @author <a href="mailto:matthewkastor@gmail.com">
 *  Matthew Christopher Kastor-Inare III </a><br />
 *  ☭ Hial Atropa!! ☭
 * @version 20130118
 * @param {String} text The text containing 
 *  <code>CDATA</code> sections to escape.
 * @returns {Array} Returns a string with escaped
 *  <code>CDATA</code> sections.
 * @see <a href="http://en.wikipedia.org/wiki/CDATA#Nesting">
 *  http://en.wikipedia.org/wiki/CDATA#Nesting</a>
 * @see <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=98168">
 *  https://bugzilla.mozilla.org/show_bug.cgi?id=98168</a>
 */
atropa.string.escapeCdata = function escapeCdata(text) {
    return String(text).replace(/]]>/g, ']]]]><![CDATA[>');
};

There are more Glorious tools in my Toolbox.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.