AS3 Trick: Wrap an XML Node's Content in CDATA

Published: Wednesday September 10, 2008 at 12:00 AM

ActionScript XML CDATA

This is very simple but I think its worth sharing since it is a bit of a shortcoming for E4X. Currently, I'm finishing up writing this small editor for a part of a page flipping content management system. Part of its role is to expose a method to JavaScript so that the web based portion of the editor can poll the flash for data that represents it's current state. We're doing this with XML but I hit a snag when I wanted one of our node's contends to be wrapped in a <![CDATA[]]>.

"E4X to CDATA: Talk to the hand."

It seems to me that this can't be done with E4X. I know some people don't "like" using CDATA but when you're dealing with textual data entered by a human you can't expect any of it to be clean so the CDATA wrapper is vital. In any event, the way to do it is a bit of a hack but it works well. Here's my simple work-around:

var unclean:String = 'Some very unsanitary ><content!><';
var xml:XML = <rootnode>
  <needs_cdata />
</rootnode>;

xml.replace('needs_cdata',
  '<needs_cdata><![CDATA[' + unclean + ']]></needs_cdata>');

Comments

Comments haven't quite been finished and imported yet. Sorry!