In a previous example, “Converting XML to objects using the Flex SimpleXMLDecoder class”, we saw how to convert an XML instance into an Object instance using the SimpleXMLDecoder class and decodeXML() method.
The following example shows how you can convert an array of objects into an XML object using the SimpleXMLEncoder class and encodeValue() method in Flex.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/04/converting-objects-to-xml-packets-using-the-simplexmlencoder-class-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:ArrayCollection id="arrColl">
<mx:source>
<mx:Array>
<mx:Object c1="1.A" c2="1.B" />
<mx:Object c1="2.A" c2="2.B" />
<mx:Object c1="3.A" c2="3.B" />
<mx:Object c1="4.A" c2="4.B" />
<mx:Object c1="5.A" c2="5.B" />
<mx:Object c1="6.A" c2="6.B" />
</mx:Array>
</mx:source>
</mx:ArrayCollection>
<mx:Script>
<![CDATA[
import mx.rpc.xml.SimpleXMLEncoder;
import mx.utils.ObjectUtil;
private function init():void {
var xml:XML = objectToXML(arrColl.source);
textArea1.text = ObjectUtil.toString(arrColl.source);
textArea2.text = xml.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());
// trace(xml.toXMLString());
return xml;
}
]]>
</mx:Script>
<mx:HDividedBox width="100%" height="100%">
<mx:TextArea id="textArea1"
editable="false"
width="100%"
height="100%" />
<mx:TextArea id="textArea2"
editable="false"
width="100%"
height="100%" />
</mx:HDividedBox>
</mx:Application>
View source is enabled in the following example.





for a project i wrote this.
this retrieve a description of a single object and after i call it in recursive way.
/** * * describe an object in xml way * */ private function objectToXML( sourceObj:Object):XML { if(!sourceObj) return null //-- get class info var calssInfo :Object = ObjectUtil.getClassInfo( sourceObj ); var xml : XML = //-- for each property for each (var propQName : QName in calssInfo.properties){ var propValue : Object = sourceObj[ propQName.localName ]; var node :XML = node.@name = propQName.localName; node.@type = flash.utils.getQualifiedClassName( propValue ) ; //– append xml.appendChild( node ) ; } return xml; }the result is like
hope helpful
I keep seeing occurrences of the tag “true” which breaks the XML parser and generates an error. Guess I can just strip it out of the XMLDocument before converting XML.
Guido Sarduchi,
Can you please log a bug with a simple, reproducible test case at http://bugs.adobe.com/flex/.
Also, if you post the bug number here, I can vote on the issue and subscribe.
Thanks,
Peter