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.

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

var xmlStr:String="<root>
<person>
<name>Rohit</name>
<surname>Agarwal</surname>
<phone>5551234</phone>
<age>24</age>
</person>
<person>
<name>Richa</name>
<surname>Mittal</surname>
<phone>5552341</phone>
<age>23</age>
</person>
<person>
<name>Puneet</name>
<surname>Jain</surname>
<phone>5553412</phone>
<age>23</age>
</person>
</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
[Bindable]
private var patArrayListCollection:ArrayCollection = new ArrayCollection();

5. Add the resultobj to the ArrayCollection

patArrayListCollection.addItem(resultObj.root.person);

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
myADG.dataProvider=tempArray;






2 comments:

Anonymous said...

Thank you, it solved my problem

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:

"
data
row
albumName_str-El disco de tu corazón-/albumName_str
albumID_int-1-/albumID_int
songID_int-1-/songID_int
songName_str-Pérfecta featuring Julieta Venegas-/songName_str
track_int-3-/track_int
-/row
-/data
"

I'm using the steps you wrote in this post