Sunday, March 3, 2013

Encode XML in Javascript

I have not worked on XML for a while since headed to JSON. In my project, I use JSON for exchanged data format, configuration file, build script and so on. I almost forgot XML in daily work. However, when we are looking at SVG which is XML syntax. I want to reiterate an old topic here. When we generate SVG text or text area data, we should do XML encode (escape). There are 2 ways to approach this.

1. XML reserved characters must be replaced with their corresponding XML entities
  • ' is replaced with '
  • " is replaced with "
  • & is replaced with &
  • < is replaced with &lt;
  • > is replaced with &gt;
if (!String.prototype.encodeXML) {
  String.prototype.encodeXML = function () {
    return this.replace(/&/g, '&amp;')
               .replace(/</g, '&lt;')
               .replace(/>/g, '&gt;')
               .replace(/"/g, '&quot;')
               .replace(/'/g, '&apos;');
  };
}
2. Use CDATA (unparsed character data)
A CDATA section starts with "<![CDATA[" and ends with "]]>". The only downside using this method is A CDATA section cannot contain the string "]]>", so we need make sure there is no nested CDATA section in XML.

No comments:

Post a Comment