Shan’s Simple Examples: Using an XML datasource with mx:ComboBox

Over the weekend I was writing a simple little app, and came across something that should have been trivial, but turned out to throw me for a loop momentarily. I needed to drive some data from XML instead of my tried-and-true ColdFusion components, and I realized I’d never done it before. So, here’s the example:

First off, you need to actually get the XML file using a HTTPService:

1
<mx:HTTPService id="sectionService" url="pet.xml" resultFormat="e4x" result="sectionResult(event)"/>

Looks simple enough, but to produce valid XML, I needed to have a root node around my other nodes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<varieties>
    <variety name="Standard"/>
    <variety name="Angora"/>
    <variety name="Satin"/>
    <variety name="Rex"/>
    <variety name="Texel"/>
    <variety name="Satin Texel"/>
    <variety name="Satin Rex"/>
    <variety name="Satin Angora"/>
    <variety name="Fuzzy"/>
    <variety name="Fuzzy Angora"/>
    <variety name="Fuzzy Hairless"/>
    <variety name="Fuzzy Hairless Angora"/>
    <variety name="Hairless"/>
</varieties>

Now, when I put this directly into a XMLList object, I got a ComboBox with one option… my entire XML packet. It took a few tries to realize that I needed to make the DataProvider only the “variety” nodes, and that was easy to do:

1
2
3
private function varietyResult(e:ResultEvent):void {
    varietyXML = XMLList(e.result.variety);
}

So, for everyone who likes to see the whole picture, like me, here’s the entire MXML code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" initialize="init()">
    <mx:HTTPService id="varietyService" url="varieties.xml" resultFormat="e4x" result="varietyResult(event)"/>
    <mx:Script>
        <![CDATA[
            import mx.rpc.events.ResultEvent;
           
            [Bindable] private var varietyXML:XMLList;
           
            private function init():void {
                varietyService.send();
            }
           
            private function varietyResult(e:ResultEvent):void {
                varietyXML = XMLList(e.result.variety);
            }
        ]]>
    </mx:Script>
    <mx:ComboBox id="variety" dataProvider="{varietyXML}" labelField="@name"/>
</mx:Application>
Comments