No Dice Required Rotating Header Image

New lines in Strings read from Xml

Are you reading Strings into your Flash application from Xml? Are your \n’s showing up as \n rather than a new line character? Are you confused why this is happening? Then you may be suffering from escapism.

But seriously…

Suppose you have this Xml string which is read by a URLLoader object:

<root>
<data message=”Hi.\nThis is on a new line” />
</root>

When this Xml document is loaded, you rip out the message with something like the following…

public function LoadXml(fileUrl:String):void
{
	var xmlLoader:URLLoader= new URLLoader();
	xmlLoader.addEventListener(Event.COMPLETE, processXml);
	xmlLoader.load(new URLRequest(fileUrl));
}
 
private function processXml(e:Event):void
{
	this._masterXml = new XML(e.target.data);
	this._message = this._masterXml.data.attribute("message");</code>
}

Then later you put this message into a TextField.

this._userMessage.text = this._message;

But then! Your text field looks like this (all on one line): Hi.\nThis is on a new line

How to fix it? Throw this in the process somewhere… after you deserialize from the Xml or before you write it to the TextField.

var newLine:RegExp = /\\n/g;
message = message.replace(newLine, "\n");

This will allow you to use \n in your Xml strings but also enjoy the benefits of multiple lines.

Hi.
This is on a new line

Be sure and tune in next time for another exciting adventure with me, Herbert “Daring” Dashwood, and my stalwart Ghoul manservant Argyle!

Leave a Reply