19
Sep
07

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.


15 Responses to “Converting XML to objects using the Flex HTTPService MXML tag”


  1. 1 mae Sep 27th, 2007 at 2:21 pm

    What about strong typing, e.g.

    var resultObj:MyCustomObject = evt.result as MyCustomObject;
    

    What’s the syntax?

  2. 2 peterd Sep 27th, 2007 at 4:08 pm

    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];
    }
    
  3. 3 peterd Sep 27th, 2007 at 4:10 pm

    Mae,

    You may want to ask on FlexCoders and see if anybody has a better solution.

    Peter

  4. 4 peterd Sep 27th, 2007 at 6:29 pm

    After a bit of Googling, this looks like it could do the trick. Darron Schall has an excellent looking example in his blog, “Convert Generic Objects into Class Instances”.

    Peter

  5. 5 mae Sep 28th, 2007 at 5:43 am

    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!

  6. 6 mae Sep 28th, 2007 at 6:15 am

    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.

  7. 7 peterd Sep 28th, 2007 at 9:22 am

    mae,

    Yeah, I’m seeing the same error (End of File). Let me know what you find out from Darron.

    Peter

  8. 8 larryh Nov 2nd, 2007 at 1:17 pm

    Mae and Peterd,

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

    Larry

  9. 9 gSOLO Nov 19th, 2007 at 1:37 pm

    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.

  10. 10 marco May 7th, 2008 at 7:07 pm

    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.

  11. 11 Andrew Oct 2nd, 2008 at 12:27 pm

    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

  12. 12 peterd Oct 2nd, 2008 at 12:43 pm

    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

  13. 13 Andrew Oct 9th, 2008 at 11:12 am

    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!

  14. 14 Andrew Oct 9th, 2008 at 12:58 pm

    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

  15. 15 peterd Oct 11th, 2008 at 4:37 pm

    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

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




September 2007
M T W T F S S
« Aug   Oct »
 12
3456789
10111213141516
17181920212223
24252627282930

Badge Farm

  • Firefox 2
  • Powered by Redoable 1.2
  • Feeds burnt by Feedburner
  • Feed