Xml – Convert XML Data to Strong Flex Type

apache-flexdata-structuresxml

A project I'm working on will pull XML from a web-server and build a data store from it. The data will have certain core fields but needs to be extendable… for example I have a and later might want to have which adds extra fields.

In the Flex app, I don't want the central data store to be working on XML objects or simply putting the properties into Objects. I want to have strong types, e.g a Person class, which are created/populated from the XML.

How can this be done in a flexible way? Is Flex able to automatically build a Person from an XML if the attribute names match, or do I need to write conversion functionality for , , etc?

Best Solution

I don't think this can be done automatically. I generally create the a class to mirror the XML structure I have and then create a static class method to create an instance of the object given an XML node. For example:

package {

  public class Foo{

     public function Foo(barparam1:String, barparam2:uint, barparam3:String, barparam4:Number){
       this._bar1 = barparam1;
       this._bar2 = barparam2;
       this._bar3 = barparam3;
       this._bar4 = barparam4;
       }

     protected var _bar1:String;
     protected var _bar2:uint;
     protected var _bar3:String;
     protected var _bar4:Number;

     public function get bar1():String{ return this._bar1; }
     public function get bar2():uint    { return this._bar2; }
     public function get bar3():String  { return this._bar3; }
     public function get bar4():Number  { return this._bar4; }

     public function toString():String{
        return "[Foo bar1:\"" + this.bar1 + "\", bar3:\"" + this.bar3 + "\", bar2:" + this.bar2 + ", bar4:" + this.bar4 + "]";
        }

     public static function createFromXml(xmlParam:XML):Foo{

        /* XML Format:
          <foo bar1="bar1value" bar2="5">
            <bar3>bar3 data</bar3>
            <bar4>10</bar4>
          </foo>
        */

       return new Foo(xmlParam.@bar1, xmlParam.@bar2, xmlParam.bar3[0], xmlParam.bar4[0]);
       }
    }
  }