Posted By

timr on 12/02/11


Tagged

xml loader as3


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

miguelrivero


Basic external XML loader


 / Published in: ActionScript 3
 

Loads a specified XML file provided in the class constructor. Dispatches an event when the XML is loaded and ready.

  1. package
  2. {
  3. import flash.events.Event;
  4. import flash.events.EventDispatcher;
  5. import flash.events.IOErrorEvent;
  6. import flash.net.URLLoader;
  7. import flash.net.URLRequest;
  8.  
  9. /**
  10. * ...
  11. * @author ...
  12. */
  13. public class LoadXML extends EventDispatcher
  14. {
  15. private var data:XML;
  16. private var loader:URLLoader;
  17.  
  18. public function LoadXML(path:String)
  19. {
  20. loader = new URLLoader();
  21. loader.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
  22. loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
  23. loader.load(new URLRequest(path));
  24. }
  25.  
  26. //---------------------------------------------------------------------------------------
  27.  
  28. private function onComplete(event:Event):void
  29. {
  30. try
  31. {
  32. data = new XML(event.target.data);
  33.  
  34. loader.removeEventListener(Event.COMPLETE, onComplete);
  35. loader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
  36.  
  37. dispatchEvent(new Event(Event.COMPLETE));
  38. }
  39. catch (error:Error)
  40. {
  41. trace("Could not load XML: " + error);
  42. }
  43. }
  44.  
  45. //---------------------------------------------------------------------------------------
  46.  
  47. private function onIOError(event:IOErrorEvent):void
  48. {
  49. trace("An error occured trying to load the XML: " + event.text);
  50. }
  51.  
  52. //---------------------------------------------------------------------------------------
  53.  
  54. public function getXML():XML
  55. {
  56. return data;
  57. }
  58.  
  59. //---------------------------------------------------------------------------------------
  60. }
  61. }
  62.  
  63. //---------------------------------------------------------------------------------------
  64. //---------------------------------------------------------------------------------------
  65. //---------------------------------------------------------------------------------------
  66. //ADD THIS TO THE TIMELINE
  67.  
  68. import flash.events.Event;
  69.  
  70. var n:LoadXML = new LoadXML("data.xml");
  71. var xml:XML;
  72.  
  73. n.addEventListener(Event.COMPLETE, onComplete);
  74.  
  75. function onComplete(event:Event):void
  76. {
  77. xml = n.getXML();
  78. }

Report this snippet  

You need to login to post a comment.