XMLParser - Painless XML Translation
- Compatibility: Flash Player 6 and later (ActionScript 2.0)
- File Size added to published SWF: About 3Kb
| |
|
Join Club GreenSock to get updates and a lot more
NOTE: If you need an AS3 version of this class, you can get it HERE
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:
<Resources>
<Book name="Mary Poppins" ISDN="1122563" />
<Book name="The Bible" ISDN="333777" />
<Novel name="The Screwtape Letters" ISDN="257896">
<Description>This is an interesting perspective</Description>
</Novel>
</Resources>
Then you could access the first book's ISDN with:
-
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:
-
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
- 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:
- url: The URL (relative or absolute) where the XML file resides that you'd like to parse
- 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:
- success: If the XML file was loaded successfully, this will be true. Otherwise, it's false.
- parsedObject: The object containing all of the parsed XML data
- original_xml: The original XML that was loaded (unparsed)
- parsedObject: [optional] A reference to an object that should be populated with the parsed XML data.
- 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.
- 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.
- 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:
- 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.)
- url: The url to which the XML should be sent.
- 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:
- success: If the XML file was loaded successfully, this will be true. Otherwise, it's false.
- parsedObject: The object containing all of the parsed XML data
- original_xml: The original XML that was loaded (unparsed)
- parsedObject: [optional] A reference to an object that should be populated with the resulting parsed XML data.
- 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.
- 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.
- 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:
- toTranslate: The ActionScript object that should be translated into XML.
- rootNodeName: [optional] An XML document must have a single root node. You can define that name here. "XML" is the default name.
- 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:
- xml: The XML that should be translated into an object.
- 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.
- 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.
- parseLineBreaks: [optional] If true, all instances of "\n" in your XML will be parsed and replaced with line breaks in Flash
- Description: Stops loading the XML document
- Description: Destroys the instance (and cancels loading the XML)
EXAMPLES
-
import gs.dataTransfer.XMLParser;
-
XMLParser.load("myDocument.xml", onFinish);
-
function onFinish($success:Boolean, $results:Object, $xml:XML):Void { //This function gets called when the XML gets parsed.
-
if ($success) {
-
trace("The first book is: "+$results.Book[0].name);
-
}
-
}
object properties become node attributes) and load the results back into an ActionScript-friendly format, do:
-
import gs.dataTransfer.XMLParser;
-
//Create an object to send an populate it with values...
-
var toSend_obj = new Object();
-
toSend_obj.name = "Test Name";
-
toSend_obj.Book = new Array();
-
toSend_obj.Book.push({title:"Mary Poppins", ISDN:"125486523"});
-
toSend_obj.Book.push({title:"The Bible", ISDN:"25478866998"});
-
//Now send the data and load the results from the server into the response_obj...
-
XMLParser.sendAndLoad(toSend_obj, "http://www.myDomain.com/myScript.php", onFinish);
-
function onFinish($success:Boolean, $results:Object, $xml:XML):Void {
-
if ($success) {
-
trace("The server responded with this XML: " + $xml);
-
trace("The server's response was translated into this ActionScript object: " + $results);
-
}
-
}
In the above example, the server would receive the following XML:
<XML name="Test Name">
<Book ISDN="125486523" title="Mary Poppins" />
<Book ISDN="25478866998" title="The Bible" />
</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.
Copyright 2008, GreenSock, Inc.
"NO CHARGE" NON-EXCLUSIVE SOFTWARE LICENSE AGREEMENT
-----------------------------------------------------------------------------
PLAIN ENGLISH SUMMARY:
- You may use the code at no charge in web sites, games, components, applications, and other software as long as end users are not charged a fee of any kind to use your product or gain access to it. It doesn’t matter if you are paid to create the site/product. If you charge end users a fee, you must sign up for a corporate Club GreenSock membership which comes with a commercial license granting you permission to do so. See http://blog.greensock.com/club/ for details.
- Since the code is updated frequently and developers are best served by having the latest version, please avoid (or at least minimize) distributing the source code outside your organization.
- Use at your own risk. I offer no warranties.
- Please respect the copyright.
-----------------------------------------------------------------------------
LEGALESE:
This is a legal agreement between you (either an individual or a single entity) and GreenSock, Inc. ("GREENSOCK") for the proprietary GreenSock ActionScript code known as TweenLite, TweenFilterLite, TweenMax, TweenGroup, OverwriteManager, and other code that is freely available for download at http://blog.greensock.com or http://www.greensock.com (this code and documentation, as well as any updates which may at GREENSOCK's sole discretion be provided to you from time to time, are referred to in this Agreement as "PROGRAM") By installing, copying, or otherwise using the PROGRAM, you agree to the terms and conditions of this Agreement. If you do not agree to the terms and conditions of this Agreement, please do not install or use the PROGRAM.
I. LICENSE
A. Subject to the terms and conditions of this Agreement, GREENSOCK hereby grants you a non-exclusive, worldwide, non-transferable right to use the PROGRAM in web sites, games, applications, components and other software for which the end user is NOT charged any fees. If you would like to use the code in a commercially licensed software product for which end users are charged a fee (either for usage or access), simply sign up for a corporate Club GreenSock membership at http://blog.greensock.com/club/.
II. LIMITATION OF LICENSE AND RESTRICTIONS
A. You agree that you will not disclose, sell, rent, license, or otherwise distribute the PROGRAM's source code or any derivative works thereof to any third party without the prior written consent of GREENSOCK. Derivative works are defined as modifications that add substantive functionality to the PROGRAM and do not include bug fixes or other minor modifications required to operate the PROGRAM as originally intended. Limited distribution of the source code to vendors as part of your Work Product is acceptable so long as they agree to the terms of this Agreement. You agree not to modify or delete GreenSock's existing copyright notice located in the source code.
B. You may use, duplicate, and distribute the compiled object code solely as embedded in a Work Product created by you, either for your own use or for distribution to a third party so long as end users of the Work Product are not charged a fee for usage. Please see http://blog.greensock.com/licensing/ for descriptions of Work Products that qualify for the "No Charge" license.
III. CONSIDERATION
A. The license rights granted to you under this Agreement are at no charge, but only in the following circumstances: If, either on your own behalf or on behalf of a third party, you incorporate the Software into a web site, software application, program or any component thereof (collectively, “Work Product”), which in the case of a web site, must be accessible to internet users without payment of a fee of any kind by a user, and in the case of a software application, program or component, neither you nor anyone to whom you distribute the Work Product charges a user a fee of any kind to use such Work Product or application, program or component into which such Work Product is embedded. The foregoing shall apply regardless of whether you are paid to create such Work Product and, under any circumstances, shall be subject to the prohibition against distribution of Source Code set forth in Section II.
B. In the event your intended use of the Software does not meet the criteria for the “no charge” license rights set forth in the immediately preceding paragraph, then you are not licensed to use the PROGRAM under this Agreement and must license the PROGRAM under GreenSock’s separate fee-based Software License Agreement which is granted to corporate Club GreenSock members (see http://blog.greensock.com/club/ for details).
IV. TITLE AND OWNERSHIP
A. The PROGRAM is licensed, not sold, and is protected by copyright laws and international treaty provisions. You acknowledge that no title to the intellectual property in the Software is transferred to you. You further acknowledge that title and full ownership rights to the PROGRAM, including all intellectual property rights therein, will remain the exclusive property of GreenSock and you will not acquire any rights to the PROGRAM except as expressly set forth in this Agreement. You agree that any copies of the PROGRAM you make will contain the same proprietary notices which appear on and in the PROGRAM.
V. DISCLAIMER OF WARRANTY AND LIMITATION OF LIABILITY
A. THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. GREENSOCK DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE PROGRAM WILL MEET YOUR REQUIREMENTS OR THAT OPERATION WILL BE UNINTERRUPTED OR ERROR FREE. GREENSOCK shall not be liable for special, indirect, incidental, or consequential damages with respect to any claim on account of or arising from this Agreement or use of the PROGRAM, even if GREENSOCK has been or is hereafter advised of the possibility of such damages. Because some states do not allow certain exclusions or limitations on implied warranties or of liability for consequential or incidental damages, the above exclusions may not apply to you. In no event, however, will GREENSOCK be liable to you, under any theory of recovery, in an amount in excess of the license fee paid by you under this Agreement. Notwithstanding anything else in this agreement, you agree to indemnify GREENSOCK, its assignees, and licensees, and hold each of them harmless from and against any and all claims, demands, losses, damages, liabilities, costs, and expenses, including legal fees.
B. GREENSOCK may, at its sole discretion, provide support services related to the PROGRAM, but has no obligation to do so.
VI. TERMINATION
GreenSock may terminate this Agreement at any time if you fail to comply with the terms and conditions of this Agreement.
VII. MISCELLANEOUS
A. This Agreement shall be construed in accordance with the laws of the State of Illinois. Should you for any reason bring a claim, demand, or other action against GREENSOCK, its agents or employees, arising out of this Agreement or the PROGRAM licensed herein, you agree to bring said claim only in the Illinois Court of Claims.
B. THIS AGREEMENT REPRESENTS THE COMPLETE AND EXCLUSIVE STATEMENT OF THE AGREEMENT BETWEEN GREENSOCK AND YOU AND SUPERSEDES ALL PRIOR AGREEMENTS, PROPOSALS, REPRESENTATIONS AND OTHER COMMUNICATIONS, VERBAL OR WRITTEN, BETWEEN THEM WITH RESPECT TO USE OF THE PROGRAM. THIS AGREEMENT MAY BE MODIFIED ONLY WITH THE MUTUAL WRITTEN APPROVAL OF AUTHORIZED REPRESENTATIVES OF THE PARTIES.
C. The terms and conditions of this Agreement shall prevail notwithstanding any different, conflicting, or additional terms or conditions which may appear in any purchase order or other document submitted by you. You agree that such additional or inconsistent terms are deemed rejected by GREENSOCK.
D. GREENSOCK and you agree that any xerographically or electronically reproduced copy of this Agreement shall have the same legal force and effect as any copy bearing original signatures of the parties.
| I'd like to donate & get bonus classes, update notifications, SVN access, and more. |
on April 4th, 2007 at 9:13 am
This looks great. How’s the performance?
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.
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. [...]
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!
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?
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.
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!
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!
on September 30th, 2007 at 1:54 pm
You totally rock! This is a wonderful timesaver and it works flawlessly. Thank you!
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!
on October 20th, 2007 at 10:14 pm
Thank you very, very much for these classes ! They are incredibly useful to me !
on October 29th, 2007 at 10:24 am
this is just great, exactly what I was looking for…
thank you very much
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!
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…
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?
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();
on January 10th, 2008 at 3:47 pm
thanx,
very usefull class.
what about special characters : “é”, “è” or “à” ?
does it work ?
bmg///
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.
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.
on January 30th, 2008 at 5:54 pm
Great suggestion, Og2t. As of version 4.6, XMLParser will parse numbers as numbers, not strings.
on February 22nd, 2008 at 3:15 pm
You sir, are a God amongst Men!
Thanks Jack!
on July 12th, 2008 at 6:52 pm
The best parser I’ve seen on the net and I’ve been around since the ice age. Very good work Jack I hope you can find the time to maintain the project.
on September 16th, 2008 at 5:54 am
jack,
This is the best xml related class i’ve seen!!
Congratulations and thanks for sharing!
on September 23rd, 2008 at 6:30 pm
Fantastic!
on October 21st, 2008 at 5:50 am
thanks jack… now i’m beginning to love XML ^^