Saturday, April 19, 2008

How to convert a XML to ArrayCollection in Flex

I wanted to use AdvancedDataGrid control of Flex 3, for which the best way to represent data is in the form of an ArrayCollection. The problem was that the data available to me was in the form of an string(XML serialized as string) and not objects. So I wanted to convert the XML to ArrayCollection.

1. The following is the string that I wanted to convert:

var xmlStr:String="<root>

2. Convert the string to XMLDocument

var xmlDoc:XMLDocument = new XMLDocument(xmlStr);

3. Convert the XMLDocument to object by using SimpleXMLDecoder

var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);

4. Declare an ArrayCollection
private var patArrayListCollection:ArrayCollection = new ArrayCollection();

5. Add the resultobj to the ArrayCollection


The important thing to note here is the composition of the patArrayListCollection is in the form
[0] --main object
[0]-sub object 1
[1]-subobject 2
[2]-subobject 3

This is not in a form that we require to make it a data provider for the AdvancedDataGrid. The Grid requires the ArrayCollection to have
objects in the form
[0]-object 1
[1]-object 2
[2]-object 3

So to get this form the following step is done

6. var tempArray:ArrayCollection=patArrayListCollection.getItemAt(0)as ArrayCollection;

7. Finally assign tempArray to the AdvancedDataGrid


Anonymous said...

Thank you, it solved my problem

Anonymous said...

Thanks a lot

Guerra said...

hello, I'm trying to use AdvancedDataGrid with a GroupingCollection, but every time I use gc.refresh() it throws TypeError: Error #1009: Cannot access a property or method of a null object reference.

Have you ever done this ? I'm using PHP.

this is the structure of the XML sent back to Flex 3:

albumName_str-El disco de tu corazón-/albumName_str
songName_str-Pérfecta featuring Julieta Venegas-/songName_str

I'm using the steps you wrote in this post