XML Reader Class

February 9th, 2007 by Slav

This class is basically a simple wrapper class around xml.load functionality.  This is how it works in it’s simplest form :

first off , you create new instance of it, and pass a callback string, which is a name of the function you want to call once the xml file has been loaded.
var reader = new com.durej.utils.XMLReader("onXMLRead");
then you add a listener to that callback :
reader.addEventListener("onXMLRead",this);
then you tell xml reader which file to load :
reader.readXMLFile("xml/sample.xml");

and that’s it ! you can sit back and relax and wait with your function to be called by the xml Reader once he’s loaded the file.

You may ask, well, that’s nice and all , but can’t I do exactly that with the build in XML.load / XML sendAndLoad functionality ? The answer is “yes, but”. This approach has couple of advantages..

With passing dynamically passing name of the callback function , you are not bound to use only “onLoad” function, you can use any function you want. 

By adding an eventDispatcher decorator, you get all the advantages of the event dispatching… Dispatching to multiple classes, turning listening on and off etc.

So the full simplest practical example of it’s use could look like this :

import new com.durej.utils.XMLReader;var reader:XMLReader = new XMLReader("onXMLRead");
reader.addEventListener("onXMLRead",this);
private function onXMLRead(eventObj:Object):Void
{
 output_txt.text = eventObj.xmlsrc;
 reader.removeEventListener(eventObj.type,this);
 delete reader;
}

reader.readXMLFile("xml/sample.xml");

of course if I was using it in the real life, I'd probably did something more useful with it , like parsed it with Xpath and stored the data in some sort of arrays or objects.

Important issue here is very loose binding. The only information you need to know is the name of the variable that contains xml, which is xmlsrc. All other variables are passed and returned back from the main class, even in the clean up code you can use eventObj.type to identify the event listener name, instead of string value.

Demo for Flash CS3

Demo for Flash 8

Posted in AS2, flash

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.