Convert Data Types: ArrayCollection, XML, Object, String

The code below demonstrates the data type conversions among basic DataTypes used most in Flex. The ‘init()’ method does to and from conversion for ArrayCollection to XML and XML to ArrayCollection

Object, String, XML, ArrayCollection

 

import mx.collections.ArrayCollection;
import mx.rpc.xml.SimpleXMLEncoder;
import mx.rpc.xml.SimpleXMLDecoder;
import mx.utils.ObjectUtil; 
  private function xmlToArrayCollection(xml:XML):ArrayCollection{                 
            var xmlDoc:XMLDocument = new XMLDocument(xml.toString());
           var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
            var resultObj:Object = decoder.decodeXML(xmlDoc);
            var ac:ArrayCollection =new ArrayCollection(Array(resultObj.root.list.source.item));
            return ac;
}
private function objectToXML(obj:Object):XML {
            var qName:QName = new QName(“root”);
            var xmlDocument:XMLDocument = new XMLDocument();
            var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
            var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
            var xml:XML = new XML(xmlDocument.toString());
            return xml;
}
private function objectToArrayCollection(obj:Object):ArrayCollection {
            var ac:ArrayCollection =  new ArrayCollection(obj as Array);
            return ac;

private function arrayCollectionToXML(ac:ArrayCollection):XML{
var xml:XML = objectToXML(ac);
return xml;
}
private function init():void{
  var arr:Array = new Array();
  arr.push({data:0,name:’deva’});
  arr.push({data:1,name:’raj’});
  var ac:ArrayCollection = new ArrayCollection(arr);
  var xml:XML = arrayCollectionToXML(ac);
var newAc:ArrayCollection = xmlToArrayCollection(xml);
trace(newAc[0][0].name);
}
private function objToStr(value:Object,indent:int =0,
                                         refs:Dictionary= null, 
                                         namespaceURIs:Array = null, 
                                         exclude:Array = null):String{
var str:String;
var refCount:int = 0;
if (value is Date)
            {
                return value.toString();
            }
            else if (value is XMLNode)
            {
                return value.toString();
            }
            else if (value is Class)
            {
                return “(” + getQualifiedClassName(value) + “)”;
            }
            else
            {
                var classInfo:Object = ObjectUtil.getClassInfo(value, exclude,
                    { includeReadOnly: true, uris: namespaceURIs });
                var properties:Array = classInfo.properties;
                str = “(” + classInfo.name + “)”;
                if (refs == null)
                    refs = new Dictionary(true);
                var id:Object = refs[value];
                if (id != null)
                {
                    str += “#” + int(id);
                    return str;
                }
                if (value != null)
                {
                    str += “#” + refCount.toString();
                    refs[value] = refCount;
                    refCount++;
                }
                var isArray:Boolean = value is Array;
                var isDict:Boolean = value is Dictionary;
                var prop:*;
                indent += 2;
                for (var j:int = 0; j < properties.length; j++)
                {
                    str = newline(str, indent);
                    prop = properties[j];
                    if (isArray)
                        str += “[";
                    else if (isDict)
                        str += "{";
                    if (isDict)
                    {
                        str += objToStr(prop, indent, refs,
                                                namespaceURIs, exclude);
                    }
                    else
                    {
                        str += prop.toString();
                    }
                    if (isArray)
                        str += "] “;
                    else if (isDict)
                        str += “} = “;
                    else
                        str += ” = “;
                    try
                    {
                        str += objToStr(value[prop], indent, refs,
                                                namespaceURIs, exclude);
                    }
                    catch(e:Error)
                    {
                        str += “?”;
                    }
                }
                indent -= 2;
                return str;
            }
}
private static function newline(str:String, n:int = 0):String
   {
       var result:String = str;
       result += “\n”;
       for (var i:int = 0; i < n; i++)
       {
           result += ” “;
       }
       return result;
   }
/* General function for Conversion (thanks, Krystian Bień)
 public function xmlToArrayCollection(xml:XML):ArrayCollection{
            var temp:String = ‘<items>’ + xml.toString() + ‘</items>’;
            xml = XML(temp);
            var xmlDoc:XMLDocument = new XMLDocument(xml.toString());
            var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
            var resultObj:Object = decoder.decodeXML(xmlDoc);
            var ac:ArrayCollection;
            ac = new ArrayCollection();
            ac.addItem(resultObj.items);
            return ac;                
        }*/

About these ads
  1. Thanks dud you did really good stuff….

    • Heru
    • July 8th, 2009

    thanks a lot, you really help me :)

    • Nikos
    • April 1st, 2010

    Awesome mate. I am sure this well presented material will be of great benefit to other wannabees like myself

    • David W
    • June 9th, 2010

    Your function objectToArrayCollection does not work. You cannot cast an Object to Array and get values, you must iterate thru it.

    • Share me your code, so i can find what went wrong..

      • An easy way to convert an object to an array is to convert the object to a string; thus, it will be a string of values seperated by ,’s. Split the string into an array by every instance of a “,”… That is if the object contains strings/numbers/etc..

  2. I am working on an application that opens XML data from an XML file. This is then converted in an Array Collection and shown in a DataGrid.

    After manipulating the DataGrid’s dataprovider Array Collection (adding, editing or deleting records) I want to save the new data back to the original XML file.

    I have used your conversion methods and they work great, but I do have one problem. When converting from AC back to XML all XML structure information is lost and default tags are used.

    Example:

    Original XML file:

    Joe
    Smith

    Mary
    Jones

    XML converted from the DataGrid’s Array Collection data provider:

    Joe
    Smith

    Mary
    Jones

    ============

    Is there any way to preserve the original XML structure or to change it subsequently?

    Or am I missing the whole point and this could be done differently and more elegantly?

    Thank you very much for your help or for at least pointing me in the right direction.

    Regards, MilanB

  3. I apologize for the re-post, just a link to a screenshot of the XML structure change, as all tags were stripped from my comment above.

    http://img714.imageshack.us/img714/7780/xmlsnip.png

      • Pedro Monteiro
      • July 20th, 2010

      I want to do like so but i cant find any help.

  4. very useful.
    Thank you

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 442 other followers

%d bloggers like this: