Home / Tutorials / ActionScript / Retrieve Data From XML File /

Flash Tutorials

Retrieve Data From XML File - Retrieve Data From XML File

Posted by : webzo on Mar 07, 2008

 

5.0/5

DOWNLOAD SOURCE FILE FOR THIS TUTORIAL

XML files are a great option to customization in flash; you can simply create a XML and tell your movie to load variables from it. Let's say you want to create a movie that randomly loads one of three images. But you think that later you may want to add more images or change their path, so you need a XML file. That's what we are going to do is this tutorial.

First create the xml file:

<xml>  
   <images>
     <a title = "pic1.jpg" />
     <b title = "pic2.jpg" />
     <c title = "pic3.jpg" />
  </images>
</xml>

You can add many more child nodes to as long as you have those images inside the folder.

Save the xml as images.xml and create a button in your project. Give it the instance name of ranImage and open the actions for the first frame. Paste this code:

var images = new XML();
images.ignoreWhite = true;
images.load("images.xml");
ranImage.onRelease = function()
{
    var images_paths = _root.images.firstChild.firstChild.childNodes;
    var ran = Math.round(Math.random() * (images_paths.length - 1));
    _root.createEmptyMovieClip("holder", 1);
    loadMovie(images_paths[ran].attributes.title, "holder");
    _root.holder._xscale = 50;
    _root.holder._yscale = 50;
}
//Here we declare a new XML object
var images = new XML()
//Sometimes white spaces in a xml file can cause problems so we tell our XML object to ignore them
images.ignoreWhite = true;
//load() function, loads our .xml
images.load("images.xml");

Here we declare a variable that corresponds to the child nodes of the images node in the xml file.

var images_paths = _root.images.firstChild.firstChild.childNodes;

Now we get a random number between 0 and the length of the images_paths array minus 1. var ran = Math.round(Math.random() * (images_paths.length - 1))

Create a holder Movie Clip. _root.createEmptyMovieClip("holder", 1);

Load the image. loadMovie(images_paths[ran].attributes.title, "holder");

Title is an attribute of this node, so we need to call it like this inside our code: (node).attributes.title

Scale the image.

_root.holder._xscale = 50; 
_root.holder._yscale = 50;

Try to add more images to the xml; you will notice that they will work exactly as they should.

This could also be very useful to create dynamic slideshows.

no comment

Add comment

Please login to post comments.