Today i was going through an requirement on how to create components in runtime where we have parse an XML as input and then create components in the stage.[codesyntax lang="actionscript3" container="none"]

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
 creationComplete="creationCompleteHandler()">

 <mx:Script>
 <![CDATA[

 import flash.display.DisplayObject;
 import mx.core.UIComponent;
 import mx.controls.ComboBox; ComboBox;
 import mx.controls.RadioButton; RadioButton;
 import mx.controls.CheckBox; CheckBox;
 import mx.controls.TextArea; TextArea;

 protected function creationCompleteHandler():void
 {
 var components:Array = getComponentsFromXML(xml.component);
 var i:int = 0;
 var n:int = components.length;
 for (i; i < n; i++)
 {
 panel.addChild(components[i] as DisplayObject);
 }
 }

 /**
 *  Parses an XML string, returns array of new components.
 */
 public function getComponentsFromXML(components:XMLList):Array
 {
 var result:Array = [];
 var child:Object;
 var component:UIComponent;
 var type:String;
 var clazz:Class;
 var i:int = 0;
 var n:int = components.length();
 for (i; i < n; i++)
 {
 child = components[i];
 type = child.@type;
 try {
 clazz = flash.utils.getDefinitionByName(type) as Class;
 } catch (error:ReferenceError) {
 traceImportError(type);
 }

 component = new clazz(); // dynamic

 var properties:XMLList = child.elements();
 var property:XML;
 var name:String;
 var value:Object;

 // for each child node
 for each (property in properties)
 {
 name = property.localName();
 value = property.toString();
 // create a more generic method to convert
 // strings to numbers and whatnot
 // this is a regular expression matching any digit
 // check out rubular.com
 if (/\d+/.test(value.toString()))
 value = Number(value);

 if (property.attribute("isStyle") == "true")
 component.setStyle(name, value);
 else
 component[name] = value;
 }
 result.push(component);
 }
 return result;
 }

 protected function traceImportError(type:String):void
 {
 trace("Please include the class '" + type + "' in the swf.");
 var names:Array = type.split(".");
 var last:String = names[names.length - 1];
 trace("import " + type + "; " + last + ";");
 }

 ]]>
 </mx:Script>

 <!-- sample data -->
 <mx:XML id="xml" source="components.xml" />

 <!-- sample container -->
 <mx:Panel id="panel" width="100%" height="100%"/>

</mx:Application>

[/codesyntax]

Live Demo

Application source