XML is the fastest and easiest way to load external data into Flash. You could take a whole class just on XML, so we will focus mainly on how to read in the file in ActionScript and use it to create scrolling message. In order to keep the example short, and to focus on the use of XML, we will start with the scrolling messages project from the lesson on arrays. Instead of putting the messages in an array, the messages are in an external XML file.
//variables
var messageNumber=0; //to keep track of which message is next
//load the xml file
var xmlFile:URLRequest = new URLRequest("messages.xml"); //same directory
var xmlLoader:URLLoader = new URLLoader(xmlFile); //starts loading the xml file
var xmlItems:XML=new XML();
//when the xml file finishes loading call initItems
xmlLoader.addEventListener("complete", initItems); //when loaded, call initItems
lblMessage.x=stage.stageWidth; //start on the right
lblMessage.autoSize = TextFieldAutoSize.LEFT;
//text field is just big enough for text so that as soon as it leaves the next one appears
function initItems(e:Event):void {
xmlItems = XML(xmlLoader.data); //parses the xml
trace(xmlItems); //try this to see what is loaded
trace("There are "+xmlItems.child("*").length()+" messages.")
trace("The first message is "+xmlItems.item[0]);
lblMessage.text=xmlItems.item[0]; //display the first message
this.addEventListener(Event.ENTER_FRAME,frames); //don't start until the xml is loaded
} //initItems
function frames(e:Event):void {
lblMessage.x--;
if(lblMessage.x<0-lblMessage.width) {
lblMessage.x=stage.stageWidth; //put the message off on the right
messageNumber++; //next message
if(messageNumber>=xmlItems.child("*").length()) { //make sure it is not too much
messageNumber=0; //if it is too much, set it back to zero
} //restart at 0
lblMessage.text=xmlItems.item[messageNumber];;
} //left the stage on left
} //frames
Download the FLA file