12-05-2008

ActionScript Loading an external XML data file with Actionscript

This bit of Actionscript 2 code will load an external xml file into your flashmovie. The processing of the xml should be done inside the onLoad event handler

var my_xml = new XML();
my_xml.ignoreWhite = true;  // ignore whitespace between xmltags. 
my_xml.onLoad = function(success){
  if (success){
    trace(this);
  }
}
my_xml.load("my_xml.xml");

Now for a simple example of processing the xml data:
let's say this is what the xml document looks like:

<?xml version="1.0"?>
<music>
	<tune>
		<title>Alive</title>
		<status>final</status>
		<image>/images/alive.jpg</image>
		<file>/sounds/Alive.mp3</file>
	</tune>
	<tune>
		<title>In love</title>
		<status>final</status>
		<image>/images/in_love.jpg</image>
		<file>/sounds/in_love.mp3</file>
	</tune>
 
</music>

This is how you would reach the contents of the example's title tags in actionscript 2:

var my_xml = new XML();
my_xml.ignoreWhite =true;
my_xml.onLoad = function(success){
  if (success){
	 trace(this.firstChild.childNodes.length)
	for (var x in this.firstChild.childNodes){
		trace(this.firstChild.childNodes[x].childNodes[0].firstChild.nodeValue)
	}
 
  }
}
my_xml.load("music.xml");

Comments:

Your comment:

»
John 25/02/2011, 1:41 pm
Problem,
I am trying to do this but the success variable always return false.
Does anyone know why this happen?
Thanks

 

[x]