GreenSock


XMLParser - Painless XML Translation

Posted in XML by jack on the February 6th, 2007


Version 4.7, Updated 2/14/2008

  • Compatibility: Flash Player 6 and later (ActionScript 2.0)
  • File Size added to published SWF: About 3Kb

Download Now
 
Donate

Join Club GreenSock to get updates and a lot more

NOTE: If you need an AS3 version of this class, let me know. Send me an e-mail at jack -at - greensock.com

Visit the new forums

DESCRIPTION

This class provides an easy way to load and/or send an XML file and parse the data into a format that's simple to work with. Every node becomes an array with the same name. All attributes are also easily accessible because they become properties with the same name. So for example, if this is your XML:

  1. <Resources>
  2.     <Book name="Mary Poppins" ISDN="1122563" />
  3.     <Book name="The Bible" ISDN="333777" />
  4.     <Novel name="The Screwtape Letters" ISDN="257896">
  5.         <Description>This is an interesting perspective</Description>
  6.     </Novel>
  7. </Resources>

Then you could access the first book's ISDN with:

  1. Book[0].ISDN

The value of a node (like the text between the <Description> and </Description> tags above) can
be accessed using the "value" property, like so:

  1. Novel[0].Description[0].value

Just remember that all nodes become arrays even if there's only one node, and attributes become properties. You can obviously loop through the arrays too which is very useful. The root
node is ignored for efficiency (less code for you to write) unless you set the keepRootNode_bol parameter to true. Also, numeric values are properly translated into numbers, not strings (as of version 4.6)

OBJECTIVES

  • Eliminate the hassle and complexity of searching through XML using methods like my_xml.firstChild.firstChild.childNodes[2].attributes.name.
  • Create an intuitive way to organize XML data while maintaining its heirarchy and naming conventions.
  • Provide a mechanism to both parse XML data into an ActionScript-friendly format and also take an ActionScript object and translate it into an XML object (maybe for sending to a server).

KEY PROPERTIES

  • percentLoaded_num: Poll this value to find out the loading progress
  • bytesLoaded
  • bytesTotal
  • xml
  • loaded_bol
  • keepRootNode_bol

USAGE


XMLParser.load(url:String, onComplete:Function, parsedObject:Object, keepRootNode:Boolean, parseLineBreaks:Boolean):XMLParser

  • Description: A static function that loads an XML document from a url (relative or absolute), parses it into the parsedObject, and then calls the onComplete (if you define one)
  • Arguments:
    1. url: The URL (relative or absolute) where the XML file resides that you'd like to parse
    2. onComplete: [optional] A reference to a function that you'd like to call as soon as the XML file has been loaded and parsed. Three parameters will get passed to that function in the following order:
      1. success: If the XML file was loaded successfully, this will be true. Otherwise, it's false.
      2. parsedObject: The object containing all of the parsed XML data
      3. original_xml: The original XML that was loaded (unparsed)
    3. parsedObject: [optional] A reference to an object that should be populated with the parsed XML data.
    4. keepRootNode: [optional] By default, the class essentially ignores the root node to make it easier for you to access data (shorter code), but if you want to keep that root node, set this value to true. Obviously it's false by default.
    5. parseLineBreaks: [optional] If you set this value to true, all instances of "\n" in your XML will be parsed and replaced with line breaks in Flash.




XMLParser.sendAndLoad(toSend:Object, url:String, onComplete:Function, parsedObject:Object, keepRootNode:Boolean, parseLineBreaks:Boolean):XMLParser

  • Description: A static method that translates an ActionScript object into XML format and sends it to a url and then returns any resulting XML (from the server) to the onComplete function.
  • Arguments:
    1. toSend: The ActionScript object that you'd like to send to the server. It does NOT need to be a simple object with only a few properties. Its properties can contain arrays (with other arrays, etc.)
    2. url: The url to which the XML should be sent.
    3. onComplete: [optional] A reference to a function that you'd like to call as soon as the XML file has been and the server has responded and the resulting XML has been parsed. Three parameters will get passed to that function in the following order:
      1. success: If the XML file was loaded successfully, this will be true. Otherwise, it's false.
      2. parsedObject: The object containing all of the parsed XML data
      3. original_xml: The original XML that was loaded (unparsed)
    4. parsedObject: [optional] A reference to an object that should be populated with the resulting parsed XML data.
    5. keepRootNode: [optional] By default, the class essentially ignores the root node to make it easier for you to access data (shorter code), but if you want to keep that root node, set this value to true. Obviously it's false by default.
    6. parseLineBreaks: [optional] If you set this value to true, all instances of "\n" in your XML will be parsed and replaced with line breaks in Flash.




XMLParser.objectToXML(toTranslate:Object, rootNodeName:String):XML

  • Description: A static function that translates any ActionScript object into an XML object. It will retain the name of each property (which ends up being a node attribute) and array (which ends up being a collection of nodes).
  • Arguments:
    1. toTranslate: The ActionScript object that should be translated into XML.
    2. rootNodeName: [optional] An XML document must have a single root node. You can define that name here. "XML" is the default name.



XMLParser.XMLToObject(xml:XML, parsedObject:Object, keepRootNode:Boolean, parseLineBreaks:Boolean):Object

  • Description: A static function that translates any XML into an object. It will retain the name of each attribute (which ends up being a property) and node value (which ends up being the "value" property of the resulting object). Similarly named node siblings are automatically dumped into an array.
  • Arguments:
    1. xml: The XML that should be translated into an object.
    2. parsedObject: [optional] If you want to add the properties/arrays to a particular object that you've already created, pass it in here, otherwise a new object will get returned with all of the properties/arrays from the parsed XML.
    3. keepRootNode: [optional] By default, the class essentially ignores the root node to make it easier for you to access data (shorter code), but if you want to keep that root node, set this value to true. Obviously it's false by default.
    4. parseLineBreaks: [optional] If true, all instances of "\n" in your XML will be parsed and replaced with line breaks in Flash




cancel()

  • Description: Stops loading the XML document



destroy()

  • Description: Destroys the instance (and cancels loading the XML)


EXAMPLES


To simply load a "myDocument.xml" document and parse the data into ActionScript-friendly values, do:

  1. import gs.dataTransfer.XMLParser;
  2. var parsed_obj = new Object(); //This will hold the parsed xml data (once the XML loads and gets parsed).
  3. XMLParser.load("myDocument.xml", onFinish, parsed_obj);
  4. function onFinish(success_boolean, results_obj, xml) { //This function gets called when the XML gets parsed.
  5.     if (success_boolean) {
  6.         trace("The first book is: "+results_obj.Book[0].name);
  7.     }
  8. }


Or to send an object to the server in XML format (remember, each element in an array becomes a node and all
object properties become node attributes) and load the results back into an ActionScript-friendly format, do:

  1. import gs.dataTransfer.XMLParser;
  2. //Create an object to send an populate it with values...
  3. var toSend_obj = new Object();
  4. toSend_obj.name = "Test Name";
  5. toSend_obj.Book = new Array();
  6. toSend_obj.Book.push({title:"Mary Poppins", ISDN:"125486523"});
  7. toSend_obj.Book.push({title:"The Bible", ISDN:"25478866998"});
  8. //Now send the data and load the results from the server into the response_obj...
  9. var response_obj = new Object(); //We'll use this to hold the parsed xml response.
  10. XMLParser.sendAndLoad(toSend_obj, "http://www.myDomain.com/myScript.php", onFinish, response_obj);
  11. function onFinish(success_boolean, results_obj, xml) {
  12.     if (success_boolean) {
  13.         trace("The server responded with this XML: "+xml);
  14.         trace("The server's response was translated into this ActionScript object: "+results_obj);
  15.     }
  16. }

In the above example, the server would receive the following XML:

  1. <XML name="Test Name">
  2.     <Book ISDN="125486523" title="Mary Poppins" />
  3.     <Book ISDN="25478866998" title="The Bible" />
  4. </XML>

Need Help?

Feel free to e-mail me a question. Or post your question on the new forums. I'd highly recommend joining Club GreenSock to get prioritized access to my time in answering your question, and so that you receive updates and lots more. When you e-mail your question, please include a simplified FLA file (and any class files) that clearly demonstrates the problem and provide a brief explanation.

PERMISSION

XMLParser is free. You're welcome to use it for commercial purposes - I only ask that you consider joining Club GreenSock. As the classes have gained popularity, I must admit that I've been a little overwhelmed by the amount of time it has taken to answer questions and continue development. Less than 1/100th of one percent of my blog visitors donate anything, so it has been difficult justifying the time away from billable jobs (of which there's no shortage!). I really LOVE writing classes like this, and if I could do it all day everyday, I would. But without enough donations, it's just not realistic.

Author: Jack Doyle, (e-mail: jack at greensock.com)
Copyright 2007, GreenSock (This work is subject to the terms here.)

21 Responses to 'XMLParser - Painless XML Translation'

Subscribe to comments with RSS or TrackBack to 'XMLParser - Painless XML Translation'.

  1. Brian said,

    on April 4th, 2007 at 9:13 am

    This looks great. How’s the performance?

  2. jack said,

    on April 4th, 2007 at 10:46 am

    Brian, I’ve been using this for quite some time and have never had any performance problems whatsoever, but I haven’t tried pushing it to its limits either by loading a 10MB XML file or anything. Nobody has reported performance problems either, so I think it’s pretty safe to say that it’ll perform quite well for you unless you get crazy with the amount XML data you load which would be more of a Flash limitation than this class.


  3. on August 3rd, 2007 at 6:22 pm

    [...] So, as you can tell, I just found GreenSock, and Jack Doyle is putting out some awesome classes.  Oddly enough, he’s in St. Charles, IL, about 20 minutes from Streamwood where my parents live (and where I intend to move back next summer).  This XMLParser basically turns all your nodes into an array that you can cycle through by the node’s name.  Excellent work, Jack. [...]

  4. Clone said,

    on August 16th, 2007 at 9:26 am

    Great class, just the thing i’ve been searching for.
    Hope i’ll be able to put it in good use.

    Cheers!

  5. Brendan said,

    on August 20th, 2007 at 10:27 pm

    This is a great class, but very annoying at the same time. For example, if I already have an XML file loaded into my movie, I cannot convert it to an object using this class. It only works if I want to load XML from an external file.

    Is there a way to convert an already-loaded XML file into an object using this class?

  6. jack said,

    on August 21st, 2007 at 1:28 am

    Brendan, you’ve got a valid point. I’ve never run into a situation where I’d want or need to load in XML without using XMLParser, but maybe you’re working with XML that’s being created from within an SWF in which case it’d be handy to have an XMLToObject() method. Wish granted. I just updated the class (v4.0) to allow for this. It should be as simple as passing your XML into the static XMLParser.XMLToObject() method and you’ll get an object returned. Enjoy.

  7. David said,

    on September 21st, 2007 at 6:08 pm

    Great class. It is very useful, and painless to use. I have a question…

    Using the XMLParser.load() method, how would you reference the attributes of the first node?

    How would I reference the “id” attribute in the following example?

    Thanks!

  8. jack said,

    on September 21st, 2007 at 11:57 pm

    David, as of version 4.4, you can now define a keepRootNode_bol parameter as true to force the class to include the root node. Keep in mind it’s false by default. So an example would be:

    XMLParser.load(”myDocument.xml”, onCompleteLoad, results_obj, true);

    The new version also adds the ability to get the bytesLoaded, bytesTotal, and percentLoaded_num for preloader visualization.

    Enjoy!

  9. George said,

    on September 30th, 2007 at 1:54 pm

    You totally rock! This is a wonderful timesaver and it works flawlessly. Thank you!

  10. Ricardo said,

    on October 19th, 2007 at 7:08 pm

    yo dude Thanks a million for these classes! and most of all THANKS for sharing them for free! this is really a good attitude.

    have a nice one!

  11. Charles said,

    on October 20th, 2007 at 10:14 pm

    Thank you very, very much for these classes ! They are incredibly useful to me !

  12. pista said,

    on October 29th, 2007 at 10:24 am

    this is just great, exactly what I was looking for…
    thank you very much

  13. michako said,

    on November 29th, 2007 at 11:52 am

    thanks for your classes Jack!
    you are a time saver.
    question: is there a possibility to make XMLParser for actionscript 3??
    that would be ideal!

  14. jack said,

    on November 29th, 2007 at 1:08 pm

    Michako, yes, I do plan on eventually porting XMLParser to AS3 but not until I have a project that requires it. I’ve got too much on my plate right now to attack it, but stay tuned…

  15. Tilman said,

    on December 22nd, 2007 at 12:19 pm

    How do I use cancel()? XMLParser.cancel() does not work, because it is not a static method. But XMLParser.load() is static, so this is how it should be used, right?

    I would like to kill the loading of the first XML, when the user clicks fast enough to fetch a second XML before the first is loaded.

    Can you give a hand?

  16. jack said,

    on December 22nd, 2007 at 12:34 pm

    Tilman, the static load() method returns an instance of the XMLParser class, and that’s what you can call cancel() on. So you could do:

    var myXMLParser = XMLParser.load(”myXML.xml”, onFinish);

    //Then, to cancel, you’d do:
    myXMLParser.cancel();

  17. brice_m_g said,

    on January 10th, 2008 at 3:47 pm

    thanx,

    very usefull class.

    what about special characters : “é”, “è” or “à” ?

    does it work ?

    bmg///

  18. jack said,

    on January 14th, 2008 at 9:56 am

    brice_m_g, from my testing, in order to get those special characters to show up inside Flash, you must:

    1) Put this code on the first frame of your SWF: System.useCodepage = true;

    2) Make sure those characters are embedded in the TextFields where you’ll use them.

  19. Og2t said,

    on January 30th, 2008 at 10:01 am

    Hey Jack! Your class is great! I was using Zeh Fernando’s XML2Object before but I think I’ll stick to yours from now on.

    I thought about one little helpful feature though: while parsing XML document, you could change the type of the value/attribute to Number (instead of being String) when it seems to be numeric.

    I found it useful while parsing XML data describing Tweens, using String type values didn’t work and it took me a while to figure it out why.

  20. jack said,

    on January 30th, 2008 at 5:54 pm

    Great suggestion, Og2t. As of version 4.6, XMLParser will parse numbers as numbers, not strings.

  21. Paul said,

    on February 22nd, 2008 at 3:15 pm

    You sir, are a God amongst Men!

    Thanks Jack!

Leave a Reply