views:

252

answers:

4

I'm capturing data from the user and writing it to an xml string like so:

var myXml:XML = {userEnteredText}

This is fine and dandy until the user gets cute with special characters like "& < >" etc. Illegal characters are also a problem like 0x19.

Is there are method that will sanatize my xml and encode special characters or will I have to roll my own?

+2  A: 

The top level function escape is one approach to this.

Joel Hooks
Except that this escape spaces as %20, which, unless you're then doing a similar conversion on the client side, is not automatically unescaped.
Jamie Love
+1  A: 

simply converting the string to a textnode should do the trick

var s:String = "test<ie>test";
var x:XML = <xml/>;
x.appendChild(s);
trace(x.toXMLString());//outputs "<xml>test&lt;ie&gt;test</xml>"

also, you can stuff all the content into CTADA ...

i'm not sure, why 0x19 should be illegal ... whitespaces and nullbytes are often dropped ... but if it is binary data you want, you should probably use base64 ... >here's a lib<

greetz

back2dos

back2dos
A: 

This is really a comment to back2dos' suggestion:

var s:String = "test<ie>test";
var x:XML = <xml/>;
x.appendChild(s);
trace(x.toXMLString());//outputs "<xml>test&lt;ie&gt;test</xml>"

On my machine, trying this generated the exception:

An ActionScript error has occurred:
TypeError: Error #1085: The element type "ie" must be terminated by the matching end-tag "</ie>".

So I'm still looking for the answer to the exact same question.

Sorry, but I don't yet have 100 points, so I can't comment directly on that post yet.

Peter V. Mørch
A: 

This does work, however:

var s:String = "test<ie>test";
var x:XML = <xml>{s}</xml>;
Alert.show(x.toXMLString());

And this shows up in the Alert: <xml>test&lt;ie&gt;test</xml>

Got it from Adobe's doc: Assembling and transforming XML objects

Peter V. Mørch