XML and Flash Actionscript made Easy | Parse XML to Object | Tutorial

    XML and flash is something that always seemed to be more complicated than it needed to be. Then I had an idea to parse the xml nodes into actionscript as objects, that would make working with xml tons easier for me, I could just parse it once and then forget about the xml, I could refer to something with the familiar dot syntax rather than worry about firstChild and nextChild and so forth…

    And then I found someone who’d already done that with XML2Object.as, here it is:

    XML@Object.as Class

    Actionscript Class:

    //////////////////
    // - Derived from code written by Alessandro Crugnola - http://www.sephiroth.it/file_detail.php?id=129#
    // - Refactored and documented by Phil Powell - http://www.sillydomainname.com
    // - 25 July 2006 - Added helper method to sanitize Windows line breaks.
    //////////////////
    // Convert an XML object to an object with nested properties.
    //
    // Example usage:
    //
    //   import net.produxion.util.XML2Object;
    //   var contentObj:Object;
    //   var xml:XML = new XML();
    //   var xmlLoaded = function( success:Boolean )
    //   {
    //    if( success )
    //    {
    //      contentObj = XML2Object.deserialize( this );
    //      this['timeline'].play();
    //    }
    //   }
    //
    //   xml.ignoreWhite = true;
    //   xml['timeline'] = this;
    //   xml.onLoad = xmlLoaded;
    //   xml.load( 'some.xml' );
    //
    /////////////////
    // What do you get back?
    //
    //   <content created="22-May-2006">
    //       <title>My Title</title>
    //       <links>
    //           <heading>Here be links!</heading>
    //           <link>http://somewhere.com</link>
    //           <link>http://somewhere-else.com</link>
    //       </links>
    //   </content>
    //
    //   Becomes:
    //
    //   contentObj.content.title.data => "My Title"
    //   contentObj.content.links.title.data => "Here be links!"
    //   contentObj.content.links.link => [Array]
    //   contentObj.content.links.link[0].data => "http://somewhere.com"
    //   contentObj.content.attributes.created => "22-May-2006"
    /////////////////
    class XML2Object {private var _result:Object;
    private var _xml:XML;
    private var _path:Object;
    private static var xml2object:XML2Object;public function XML2Object()
    {
    this._result = new Object();
    }

    public static function deserialize( xml:XML ):Object
    {
    xml2object = new XML2Object();
    xml2object.xml = xml;
    return xml2object.nodesToProperties();
    }

    public function get xml():XML
    {
    return _xml;
    }

    public function set xml( xml:XML ):Void
    {
    this._xml = xml;
    }

    private function nodesToProperties( parent:XMLNode, path:Object, name:String, position:Number ):Object
    {
    var nodes:Array;
    var node:XMLNode;

    path == undefined ? path = this._result : path = path[name];
    if( parent == undefined) parent = XMLNode( this._xml );

    if( parent.hasChildNodes() )
    {
    nodes = parent.childNodes;
    if (position != undefined) path = path[position];

    while( nodes.length &gt; 0 )
    {
    node = XMLNode( nodes.shift() );

    if ( node.nodeName != undefined )
    {
    var obj = new Object();
    obj.attributes = node.attributes;
    obj.data = sanitizeLineBreaks( node.firstChild.nodeValue );

    if( path[node.nodeName] != undefined )
    {

    if( path[node.nodeName].__proto__ == Array.prototype )
    {
    path[node.nodeName].push( obj );
    }
    else
    {
    var copyObj = path[node.nodeName];
    delete path[node.nodeName];
    path[node.nodeName] = new Array();
    path[node.nodeName].push( copyObj );
    path[node.nodeName].push( obj );
    }
    position = path[node.nodeName].length - 1;
    }
    else
    {
    path[node.nodeName] = obj;
    position = undefined;
    }
    name = node.nodeName;
    }

    if( node.hasChildNodes() )
    {
    this.nodesToProperties( node, path, name, position );
    }
    }

    }
    return this._result;
    }

    private function sanitizeLineBreaks( raw:String )
    {
    if( raw.indexOf( "\r\n" ) &gt; -1 )
    {
    return raw.split( "\r\n" ).join( "\n" );
    }
    return raw;
    }
    }

    Example:

    Get Adobe Flash player

    Source:

    Here is my example file. But since you cant really see Objects in the code on the stage, I’ve included a recursive trace function to loop through the object and print the data.

    import XML2Object;

    var xmlObject:Object;
    var xml:XML = new XML();

    var xmlLoaded = function( success:Boolean ){
    if( success ) {
    xmlObject = XML2Object.deserialize( this );
    this['timeline'].play();
    recurseTrace(xmlObject, " ");
    myTrace("\n\n")
    myTrace("xmlObject.catagories.catagory[10].name.data = "+xmlObject.catagories.catagory[10].name.data);
    }
    }

    xml.ignoreWhite = true;
    xml.onLoad = xmlLoaded;
    xml.load( 'sampleXML.xml' );

    function recurseTrace(info:Object, indent:String) {
    for (var i in info) {
    if (info[i] == null){}
    else if (typeof info[i] == "object") {
    myTrace(indent + i + " -");
    recurseTrace(info[i], indent);
    }
    else {
    myTrace(indent + i + " = " + info[i] +", ");
    }
    }
    }

    function myTrace(myLine:String){
    feedback.text += "|"+myLine;
    trace(myLine);
    }

    And here’s my sample xml file: (it’s the same one I use in my Dynamic Flash Scrolling Link List files)

    <catagories>
    <catagory>
    <name>3D</name>
    <url>http://circlecube.com/tag/3d/</url>
    </catagory>
    <catagory>
    <name>abstract</name>
    <url>http://circlecube.com/tag/abstract/</url>
    </catagory>
    <catagory>
    <name>actionscript</name>
    <url>http://circlecube.com/tag/actionscript/</url>
    </catagory>
    <catagory>
    <name>animation</name>
    <url>http://circlecube.com/tag/animation/</url>
    </catagory>
    <catagory>
    <name>blog</name>
    <url>http://circlecube.com/tag/blog/</url>
    </catagory>
    <catagory>
    <name>book</name>
    <url>http://circlecube.com/tag/book/</url>
    </catagory>
    <catagory>
    <name>CG</name>
    <url>http://circlecube.com/tag/cg/</url>
    </catagory>
    <catagory>
    <name>charcoal</name>
    <url>http://circlecube.com/tag/charcoal/</url>
    </catagory>
    <catagory>
    <name>circle cube</name>
    <url>http://circlecube.com/tag/circle-cube/</url>
    </catagory>
    <catagory>
    <name>collage</name>
    <url>http://circlecube.com/tag/collage/</url>
    </catagory>
    <catagory>
    <name>color</name>
    <url>http://circlecube.com/tag/color/</url>
    </catagory>
    <catagory>
    <name>css</name>
    <url>http://circlecube.com/tag/css/</url>
    </catagory>
    <catagory>
    <name>drawing</name>
    <url>http://circlecube.com/tag/drawing/</url>
    </catagory>
    <catagory>
    <name>dreamweaver</name>
    <url>http://circlecube.com/tag/dreamweaver/</url>
    </catagory>
    <catagory>
    <name>experiment</name>
    <url>http://circlecube.com/tag/experiment/</url>
    </catagory>
    <catagory>
    <name>film</name>
    <url>http://circlecube.com/tag/film/</url>
    </catagory>
    <catagory>
    <name>final cut</name>
    <url>http://circlecube.com/tag/final-cut/</url>
    </catagory>
    <catagory>
    <name>flash</name>
    <url>http://circlecube.com/tag/flash/</url>
    </catagory>
    </catagories>

    Download:

    Here’s the XML2Object.as class: XML2Object.as class

     

    Here’s a zip containing everything and the working example: xmlToObject.zip

    This entry was posted in tutorial and tagged , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

    17 Comments

    1. Posted August 28, 2008 at 1:45 am | Permalink

      Wow. Thank you! In the past I’ve been in too much of a hurry to even try to work with ActionScript’s stupidly complicated XML handling. On one recent project, I just imported the whole XML file as text, and parsed it using string functions for the bits I needed. (Not very elegant at all, I know.. but in terms of coding time, it was much quicker).

      This is extremely sweet though. (In fact, what you’ve done here is sort of how I thought XML handling in ActionScript *would* work before I found out otherwise).

      Very nice. Very nice.

      -Popo

    2. Posted September 11, 2008 at 12:57 am | Permalink

      Very nice.

      great for transferring info to and from Flash using xml and easily
      being able to grab info.

      Phil

    3. Mark
      Posted October 16, 2008 at 5:38 am | Permalink

      Can any one help me with this

      Create a Flash Movie: 550 x 400 pixels.
      2. Write 2 external ActionScript files, one of which MUST be the Document
      Class.
      3. Code a Rectangle with a Blue border and fill it with a Red and Greed Gradient
      at a 45 degree angle. (Use the second ActionScript file for this)
      4. Add 10 instances of this Rectangle to the stage, randomly placing them along
      the TOP of the movie, one per second, for 10 seconds.
      5. As soon as a square is added, it should start falling to the bottom of the
      movie, where it bounces before coming to a stop.
      · There should be NO Timeline animation of any kind, in-fact, there should be
      nothing on any Frame of the .fla file at all.
      · The Library of the .fla file should also be completely EMPTY.
      · You are allowed to use no more than 60 lines of code, spread over the 2
      allowed ActionScript Files.
      · You must send the .fla file, together with the 2 ActionScript files in for
      evaluation.

    4. Posted October 17, 2008 at 7:13 am | Permalink

      @Mark – Looks like a fun assignment! Good luck with that.

      This post may help you and I’d definitely recommend Keith Peters for the background on gravity

    5. Michael
      Posted November 19, 2008 at 2:46 pm | Permalink

      Evan,
      do you have an AS3 version of this?

      Thanks.

    6. Posted May 8, 2009 at 6:31 am | Permalink

      Yup, it’s all ActionScript 2. Thinks like XMLNode are not working with only 1 parameter in AS3 etc.

    7. Posted July 2, 2009 at 4:54 am | Permalink

      Xml to Object, is that not what e4x does? wich is available in my Flex/Air projects

      I am looking for a deserialize to a custom type

    8. Posted July 2, 2009 at 6:42 am | Permalink

      @Bart – Yes, but note this is for as2, this xml to object is pre e4x, there are multiple ways to do it, but some as2 developers still could find uses for it. Good luck with the deserialiser.

    9. Posted August 11, 2009 at 3:22 pm | Permalink

      Wowzers..

      I’m writing some code to deal with a massive amount of XML data and faced with bug fixing in the dark I was ready to bang my head against a brickwall until I saw your little trace function there.. that is a real life saver.. thanks a lot for that!!

      Cheers
      M.

    10. Posted December 3, 2009 at 6:02 pm | Permalink

      Evan,

      Awesome class! I’m stuck on AS2 for a project that won’t move to AS3 any time soon. I was parsing my own XML, but this is much easier. It works great on my little XML file. How does it do with large files?

    11. Posted December 7, 2009 at 10:20 am | Permalink

      Not to sure about large files, I hadn’t tested this too extensively. Let us know what you find if you don’t mind, Thanks!

    12. Posted February 22, 2010 at 3:57 pm | Permalink

      Does anyone know how to apply this class to an XML which is not a file?
      I have PHP function which imports data back into Flash in XML form, but I’m having problems parsing it.

      Thanks in advance,
      Mariano

    13. davea0511
      Posted March 3, 2010 at 4:56 am | Permalink

      this is also worth checking out … http://indivision-codebase-as2.googlecode.com/files/indivision_codebase2-080629-all.zip

      look in the classes/net/indivision/data directory and there is a great XML->Obj and Obj-> XML tool.

    14. Josh
      Posted September 6, 2010 at 11:00 am | Permalink

      Hey Evan,
      nice tutorial, thank you. I found this one after viewing your AS2 version. I only know AS3 and am trying to use this example but in the simplicity you did the AS2 tutorial.

      So right now I’m trying to strip everything out and have my html page with the embedded flash simply display all the hex codes for your colour variable, in other words, just a list of the items separated by the commas.

      Thing is I keep getting errors and cannot exactly tell what code has to stay and what can go…..any help?!

    15. davea0511
      Posted September 10, 2010 at 4:18 am | Permalink

      On a related note: “readable object serialization” … the routine I’ve linked below doesn’t convert to or from XML, but it does take your flash objects and serializes them into an easy-to-read string, from which it can recreate the object. MUCH easier to read datafiles in this format compared to XML datafiles:

      http://kionetics.com/programmingProjects/readableSerialization/readableSerialization.html

      It’s just in AS2, but I’d like to do an AS3 version some time in the future.

      Of course, ideally you want many if not most of your parameters stored in individual database fields so this seems moot, but you may have complex data objects that need no parsing outside your program, and which you might want to inspect or view as a well formatted object, in which case it makes sense to serialize them with this routine and store it as a string for each record in a single database field. It’s nice keeping your db-field-count at a minimum too.

    16. Posted February 24, 2011 at 6:59 am | Permalink

      I need to find id say 44. how do I make a method that from this CML finds the right id and (44) and return me a line Parent = -9?

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    • Recent Posts

      WordPress updates plugin directory

      New additions to the plugin directory include: favorites, incorporating support forums into it's own tab for each plugin as well as support stats being displayed! Great! I think we also need the ability to give plugins ratings and reviews (bonus points if it can be done from within a wordpress admin dashboard when installing plugins). [...]

      Short Head

      Use zipf's short head to tune your website rather than redesign the whole thing. To make a website successful it needs to meet the needs of the users. Find out what those needs are by using the short head philosophy to equate most searched things as the biggest needs of the users. Use personas to [...]

      Img Set?

      Great article at a list apart discusing the state of the industry regarding responsive images. This picks apart the set attribute of the img element from a surprisingly objective view coming from someone so close to the picture element. Insightful discussion about the principle behind the proposals than the actual solution too. If the working [...]

      Triudo

      A mesmerizing animated triangle-ish shape form. Embedded Link triduo triduo Tweet

      Git – the paradigm shift

      A great developer story about the differences on what Git is vs other version control and what Git is not. This is how we should learn it. I heard over and over that it was distributed, but never grasped what that meant, so here are a few links and explanations that will help unlearn version [...]

      Tweening Lib comes to Javascript!

      I'm very excited to share the news that the tween library from GreenSock (hands down the best tweening library I used in flash) is not ported for use in javascript! This will be great! I missed that simple syntax from as3 when animating javascript, and now I can have my cake and eat it too. [...]

      Responsive CSS Tricks

      Here are a few useful css tricks to remember when building responsive design sites from web designer wall Embedded Link 5 Useful CSS Tricks for Responsive Design Making the design to be responsive is very easy as shown in my Responsive Design in 3 Steps tutorial, but maintaining the elements to look aesthetically balanced on [...]

      Picture element of srcset attribute?

      Bruce details the reasons and story behind the srcset attribute which is now introduced as an alternative to the picture element. Some aspects of the attribute are nice (like the fact that it's an attribute and not a new element, so it's creating up new elements with for problems. It's adapting currently used elements to [...]

      SVG Preloader with Raphael JS

      Here's a very creative use of using a newly available technology. Using svg graphics which are very lightweight, for a website preloader. I like the animation used as well. Embedded Link Make a stylish preloader with SVG | Tutorial | .net magazine Many sites neglect users with slow connections. Ian Culshaw explains how to use [...]

      CSS3 Button/Icon set

      I've been secretly hoping to see a few of these pop up once the whole icon font idea spread through the nets. I really like this idea and it's a very nice implementation too! I only see some quality issues on a couple of the icons (such as youtube), but it's awesome and I hope [...]

    • Recent Comments

      Bruce Brownlee

      Bruce Brownlee

      Ah IE6. I'd have 2 more years of sleep without IE6. Margin doubling, no properties,...
      versaena

      versaena

      how to give color at runtime…… thank you
      Mobile Websites

      Mobile Websites

      I disagree, mobile websites are the future – desktop websites and mobile websites...
      Matt Fasick

      Matt Fasick

      That's cool. I like the ripple effect as well.
      Nico

      Nico

      hi! really great job guy! very impressive.. just a question… do u have a solution to do a refresh...
      Evan Mullins

      Evan Mullins

      Agreed! I've just seen some people get pretty heated about separating all functionality...