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

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

View or Add Comments

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

 
  • From Paul
  • Date Monday October 20, 2008 at 10:58 PM

Just stumbled on this solution:

http://snipplr.com/view/4776/create-cdata-tags-between-xml-nodes-using-as/

I like it for it's cleanliness but it requires that a method be declared so it really becomes a question of what works best for your situation.

 

Add a Comment

*email addresses are not made public

*uses a small subset of markdown for formatting and links