Saturday, March 1, 2008

Reading remote XML data in Flex

We all know that Flex 2 provides ArrayCollection , XMLListCollection to read XML and consume the data.
However in case the XML contains only a single set of Data entries ArrayCollection are not the right solution.
Assuming the XML is
<dataroot>
<Capital>
<city>Delhi</city>
<country>India</country>
</Capital>
</dataroot>


In order to read this XML you have two ways to do

<mx:HTTPService id="rpcPatHTTP" url="sample.xml" resultFormat="object" result="handlerCapital(event)" />

<mx:Script>
<![CDATA[

[Bindable]
var myAC:ArrayCollection = new ArrayCollection();
private function handlerCapital(event:ResultEvent):void
{
myAC = event.result.dataroot.Capital as ArrayCollection


}

]]>
</mx:Script>

In the above case if you try to get the length of the myAC ArrayCollection, you will get 0
so
myAC.length will give 0

In such cases you should use the XMLListCollection. So the above example will be rewritten as

<mx:HTTPService id="rpcPatHTTP" url="sample.xml" resultFormat="e4X" result="handlerCapital(event)" />

<mx:Script>
<![CDATA[

[Bindable]
var myXML:XMLListCollection;
private function handlerCapital(event:ResultEvent):void
{
myXML = new XMLListCollection(event.result.Capital);

}

]]>
</mx:Script>


Now if you try to find the length of the collection you will get 1 so myXML.length will give 1, which is correct.

So my recommendation is use XMLListCollection over ArrayCollections to store the incoming remote data since you never know the number of entries in the XML file

No comments: