Loading an XML Config File with AS3


/ Published in: ActionScript 3
Save to your folder(s)



Copy this code and paste it in your HTML
  1. package
  2. {
  3.  
  4. import flash.display.Loader;
  5. import flash.display.MovieClip;
  6. import flash.events.Event;
  7. import flash.net.URLLoader;
  8. import flash.net.URLRequest;
  9.  
  10. public class Main extends MovieClip
  11. {
  12.  
  13. private var configXMLPath:String;
  14.  
  15. public function Main()
  16. {
  17. //Set the path of the xml file that defines the loaded images
  18. if (root.loaderInfo.parameters.configXMLPath)
  19. {
  20. //This allows you to define the location of the config file in the embed parameters on the page
  21. configXMLPath = root.loaderInfo.parameters.configXMLPath;
  22. }
  23. else
  24. {
  25. //Default to a config.xml file at the same level as the swf.
  26. configXMLPath = "config.xml";
  27. }
  28.  
  29. LoadConfigXML();
  30. }
  31.  
  32.  
  33. public function LoadConfigXML():void
  34. {
  35. var xmlURL:String = configXMLPath;
  36.  
  37. var configRequest:URLRequest = new URLRequest();
  38. configRequest.url = xmlURL;
  39.  
  40. var assetLoader:URLLoader = new URLLoader();
  41. assetLoader.addEventListener(Event.COMPLETE, ParseConfigXML);
  42. assetLoader.load(configRequest);
  43. }
  44.  
  45. private function ParseConfigXML(e:Event):void
  46. {
  47.  
  48. var configXML:XML = new XML(e.target.data);
  49. if (configXML.title.@path)
  50. {
  51. addImageToStage(configXML.title.@path, Number(configXML.title.@x), Number(configXML.title.@y));
  52. }
  53.  
  54. if (configXML.images)
  55. {
  56. for each (var image:XML in configXML.images.*)
  57. {
  58. addImageToStage(image.@path, Number(image.@x), Number(image.@y));
  59. }
  60. }
  61.  
  62. }
  63.  
  64. private function addImageToStage(imgURL:String, imgX:Number, imgY:Number):void
  65. {
  66. try
  67. {
  68. var imgLoader:Loader = new Loader();
  69. var imageReq:URLRequest = new URLRequest(imgURL);
  70. imgLoader.load(imageReq);
  71. imgLoader.x = imgX;
  72. imgLoader.y = imgY;
  73. addChild(imgLoader);
  74. }
  75. catch (err:Error)
  76. {
  77. //Handle error here.
  78. trace(err.message);
  79. }
  80.  
  81. }
  82.  
  83. }
  84. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.