Converting XML to objects using the Flex HTTPService MXML tag

The following example shows how you can convert an XML file loaded at run-time using the HTTPService tag, into an ActionScript Object by simply setting the resultFormat property to “object”.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/19/converting-xml-to-objects-using-the-flex-httpservice-mxml-tag/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="serv.send();">

    <mx:Script>
        <![CDATA[
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;

            private function serv_result(evt:ResultEvent):void {
                var resultObj:Object = evt.result;
                /* Assign the values... */
                nameText.text = resultObj.album.name;
                img0Text.text = resultObj.album.images.image[0];
                img1Text.text = resultObj.album.images.image[1];
                img2Text.text = resultObj.album.images.image[2];
            }

            private function serv_fault(evt:FaultEvent):void {
                /* Show the error label. */
                error.text += evt.fault.faultString;
                error.visible = true;
                /* Hide the form. */
                form.visible = false;
            }
        ]]>
    </mx:Script>

    <mx:String id="XML_URL">album.xml</mx:String>

    <mx:HTTPService id="serv"
            url="{XML_URL}"
            resultFormat="object"
            result="serv_result(event);"
            fault="serv_fault(event);" />

    <mx:ApplicationControlBar dock="true">
        <mx:Label text="{XML_URL}" />
    </mx:ApplicationControlBar>

    <mx:Label id="error"
            color="red"
            fontSize="36"
            fontWeight="bold"
            visible="false"
            includeInLayout="{error.visible}"/>

    <mx:Form id="form"
            includeInLayout="{form.visible}">
        <mx:FormItem label="resultObj.album.name:">
            <mx:Label id="nameText" />
        </mx:FormItem>
        <mx:FormItem label="resultObj.album.images.image[0]:">
            <mx:Label id="img0Text" />
        </mx:FormItem>
        <mx:FormItem label="resultObj.album.images.image[1]:">
            <mx:Label id="img1Text" />
        </mx:FormItem>
        <mx:FormItem label="resultObj.album.images.image[2]:">
            <mx:Label id="img2Text" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>

View album.xml

<?xml version="1.0" encoding="utf-8"?>
<album>
    <name>One</name>
    <images>
        <image>image1.jpg</image>
        <image>image2.jpg</image>
        <image>image3.jpg</image>
    </images>
</album>

View source is enabled in the following example.

20 thoughts on “Converting XML to objects using the Flex HTTPService MXML tag

  1. mae,

    I’m not sure of the *best* way, but I’ve found this works (but almost feels a little “hacky” to me):

    MyCustomObject.as

    package {
        import mx.utils.ObjectProxy;
    
        public class MyCustomObject extends Object {
            public var name:String;
            public var images:ObjectProxy;
    
            public static function create(value:Object):MyCustomObject {
                var co:MyCustomObject = new MyCustomObject();
                co.name = value.name;
                co.images = value.images;
                return co;
            }
        }
    }
    

    main.mxml — snippet

    private function serv_result(evt:ResultEvent):void {
        var resultObj:MyCustomObject = MyCustomObject.create(evt.result.album as Object);
        /* Assign the values... */
        nameText.text = resultObj.name;
        img0Text.text = resultObj.images.image[0];
        img1Text.text = resultObj.images.image[1];
        img2Text.text = resultObj.images.image[2];
    }
    
  2. peter,

    Thanks. I saw that article a while back and didn’t understand it’s importance (I’m new at flex/actionscript). I’ll give it a shot.

    Thanks again!

  3. Peter,

    I’m getting the following error with Darron’s code (I emailed him as well).

    Error #2030: End of file was encountered.

    In ByteArray/readObject()

    I’m returning an object from an ASP.Net Web service.

    Any ideas? My resultFormat is object.

    Thanks.

  4. Mae and Peterd,

    I’m also encountering this issue… has anyone figured why this message occurs? Thanks!

    Larry

  5. Are you using an ArrayCollection and or are you using the default makeObjectsBindable and the result contains an Array? In my case, I believe that is where it choking.

  6. Hi Peter

    i read the other topic on your blog, we can use the function at the below to get the xml’s data on the data grid

    private function resultHandler(event:ResultEvent):void	{
    	xmlData = event.result.mynode.childnode.source as Array;
    	xmlDataAC.source = xmlData;
    }
    

    but in this case the xml format is has different child node
    One

    image1.jpg
    image2.jpg
    image3.jpg

    can i still use xmlData = event.result.album.name.source as Array; and
    xmlData2 = event.result.album.image.source as Array; to get the data ?? i have tried that they were not work. do you have any suggestion to get the data from different node easily ?? because img0Text.text = resultObj.album.images.image[0]; is so hard to use when my xml has alot/ unknow lenght node.

  7. Peter,

    I’m having an issue with understanding Flex’s HttpService calls. I’m looking to do something similar to an HTML Select with my form. I currently have 1 List box and 3 comboBox’s receiving XML data from my MySQL DB.

    It is currently just populating the Label, however when I go to insert/update to the database I want to insert the Value (or Key) and not the label. How could I do this? I thought if I returned the result from the HTTPService as a result it would look more like an HTML Select, however I can’t think of how the combobox or list will know what to submit when a particular Label is selected… since they are usually a selectedItem or selectedIndex.

    Sorry for my confusing text either way, any help would be greatly appreciated.

    Andy

  8. Andrew,

    I typically use <ComboBox>.selectedItem.<fieldName>, or, something like the following:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    
        <mx:Array id="arr">
            <mx:Object label="One" data="1" />
            <mx:Object label="Two" data="2" />
            <mx:Object label="Three" data="3" />
            <mx:Object label="Four" data="4" />
        </mx:Array>
    
        <mx:ComboBox id="comboBox" dataProvider="{arr}" />
        <mx:Label text="comboBox.selectedItem.label={comboBox.selectedItem.label}" />
        <mx:Label text="comboBox.selectedItem.data={comboBox.selectedItem.data}" />
    
    </mx:Application>
    

    Hope that helps,
    Peter

  9. Peter,

    I totally understand how that works… but how can I do that when I’m returning XML from a DB?

    What would my XML need to look like? Also, wouldn’t I have to put the XML into a XMLListCollection or XMLList?

    My XML is currently returning something like this:

    Peter
    Andrew
    ….
    and so on…..

    Would I want to include the employees primary key in the XML?

    Peter
    20
    Andrew
    2

    Basically, I understand the logic behind .selectedItem…. but am really confused how to work with the XML as supposed to hardcoding my Object Array.

    Thanks!

  10. to simplify what I’m saying… i want to mimic the:

        <mx:Array id="arr">
            <mx:Object label="One" data="1" />
            <mx:Object label="Two" data="2" />
            <mx:Object label="Three" data="3" />
            <mx:Object label="Four" data="4" />
        </mx:Array>
    

    but coming from an HTTPService from a .php file outputting XML

  11. Andrew,

    You could try setting the resultFormat property on the HTTPService tag to “array” when loading an XML file and see what type/format of an ArrayCollection object that returns. To get at the underlying Array object, you would just access the ArrayCollection object’s source property.

    Apart from that, if you have a specific format you want, I’d suggest just writing your own code. Take the last result from the HTTPService tag, and loop over the ArrayCollection/XML results and construct your own custom array of objects in the specific format you need.

    Peter

  12. Nice example.

    But my XML file have hyphens in the tags. And i cant get it to work.
    How would i do if for example the album tags instead of <album> was <album-album>?

    1. @Simon,

      Try this:

      private function serv_result(evt:ResultEvent):void {
          var resultObj:Object = evt.result;
          /* Assign the values... */
          nameText.text = resultObj['album-album'].name;
          img0Text.text = resultObj['album-album'].images.image[0];
          img1Text.text = resultObj['album-album'].images.image[1];
          img2Text.text = resultObj['album-album'].images.image[2];
      }

      Assuming you had the following XML packet:

      <?xml version="1.0" encoding="utf-8"?>
      <album-album>
          <name>One</name>
          <images>
              <image>image1.jpg</image>
              <image>image2.jpg</image>
              <image>image3.jpg</image>
          </images>
      </album-album>

      Peter

  13. Hi,
    Nice tutorial. But I also want to validate my XML against a given XSD schema. Could you please tell me about how to do that.

    Thanks,
    Amit.

  14. Thank you so much for this example…. I was struggling to get the datas in dataGrid…. Now im clear. Thanq.

  15. Excelent!! thanks Peter, i have a little question (too late XD):

    if on the xml file i have more than one album, something like:

    One

    image1.jpg
    image2.jpg
    image3.jpg

    Two

    asdf.jpg
    qwer.jpg
    zcxv.jpg

    How could i acces to the album Two, image 3???
    How does the object would be?

    Maybe something like:
    resultObj.albums.album[2].images.image[3]; ?????

    thanks.

Comments are closed.