Xml – Flex: Convert ArrayCollection to XML

apache-flexarraycollectionxml

In Flex, it's easy to convert the XML to Object and to ArrayCollection by using

var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
decoder.decodeXML( xml );

But is there a good way to convert ArrayCollection to XML.
I have search a while on the internet and havn't found any answer.

Thanks.

Best Answer

Have a look at this example, which uses SimpleXMLEncoder:

<mx:Script>
    <![CDATA[

        import mx.rpc.xml.SimpleXMLEncoder;
        import mx.utils.ObjectUtil;
        import mx.utils.XMLUtil;
        import mx.collections.ArrayCollection;

        private var items:ArrayCollection;

        private function onCreationComplete():void
        {
            var source:Array = [{id:1, name:"One"}, {id:2, name:"Two"}, {id:3, name:"Three"}];
            var collection = new ArrayCollection(source);

            trace(objectToXML(collection.source).toXMLString());
        }

        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;
        }

    ]]>
</mx:Script>

...which produces the following XML:

<root>
  <item>
    <id>1</id>
    <name>One</name>
  </item>
  <item>
    <id>2</id>
    <name>Two</name>
  </item>
  <item>
    <id>3</id>
    <name>Three</name>
  </item>
</root>

I should note that got the objectToXML function from Peter de Haan's blog, but folks have apparently had a few problems with the SimpleXMLEncoder class. In my own tests, encoding simple objects works well (as indicated above), but complex types tend to produce unpredictable results. (For example, encoding an array of Font objects produced a long list of empty item nodes.)

But depending on the types you're attempting to serialize, this approach might work out just fine for you. Hope it helps!