Nathan Smith
Nathan Smith

Reputation: 37547

How do you encode XML safely with ActionScript 3?

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?

Upvotes: 2

Views: 4713

Answers (4)

back2dos
back2dos

Reputation: 15623

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<

Upvotes: 3

Peter V. M&#248;rch
Peter V. M&#248;rch

Reputation: 15927

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

Upvotes: 3

Peter V. M&#248;rch
Peter V. M&#248;rch

Reputation: 15927

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.

Upvotes: 0

Joel Hooks
Joel Hooks

Reputation: 6565

The top level function escape is one approach to this.

Upvotes: 1

Related Questions