Converting XML to objects using the Flex HTTPService MXML tag

by Peter deHaan on September 19, 2007

in HTTPService, XML

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.

{ 18 comments… read them below or add one }

1 mae September 27, 2007 at 2:21 pm

What about strong typing, e.g.

var resultObj:MyCustomObject = evt.result as MyCustomObject;

What’s the syntax?

Reply

2 peterd September 27, 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];
}

Reply

3 peterd September 27, 2007 at 4:10 pm

Mae,

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

Peter

Reply

4 peterd September 27, 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

Reply

5 mae September 28, 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!

Reply

6 mae September 28, 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.

Reply

7 peterd September 28, 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

Reply

8 larryh November 2, 2007 at 1:17 pm

Mae and Peterd,

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

Larry

Reply

9 gSOLO November 19, 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.

Reply

10 marco May 7, 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.

Reply

11 Andrew October 2, 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

Reply

12 peterd October 2, 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

Reply

13 Andrew October 9, 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!

Reply

14 Andrew October 9, 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

Reply

15 peterd October 11, 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

Reply

16 Simon October 6, 2009 at 2:44 pm

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>?

Reply

17 Peter deHaan October 7, 2009 at 6:55 pm

@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

Reply

18 Amit December 22, 2009 at 10:46 am

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.

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: