Flex3 Object to xml
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
//自己遍历Object转换(属性方示表现)
public function objectToXml1(obj:Object,name:String):XML{
var result : XML;
var info:Object = ObjectUtil.getClassInfo(obj);
if(name==null)
name = info.name;
var line:String = "<" + name;
for each (var qn : QName in info.properties){
line += " ";
line = line + qn.toString() + "=";
line = line + "\"" + obj[qn.toString()] + "\"";
}
line += "/>"
result = new XML(line);
return result;
}
//自己遍历Object转换(子节点方示表现)
public function objectToXml2(obj:Object,name:String):XML{
var result : XML;
var info:Object = ObjectUtil.getClassInfo(obj);
if(name==null)
name = info.name;
result = new XML("<" + name + "></"+ name + ">");
for each (var qn : QName in info.properties){
var val : Object = obj[qn.toString()];
if(ObjectUtil.isSimple(val))
result[qn.toString()] = val;
else
result.appendChild(objectToXml2(val,qn.toString()));
}
return result;
}
//通过SimpleXMLEncoder转换
private function objectToXml3(obj:Object,name:String):XML {
var qName:QName = new QName(name);
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;
}
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
var testPerson:Object = {name:"xxx",role:"leader",phone:"123456",email:"mail@mail.com",image:"ttt.swf"};
var xml1:XML = objectToXml1(testPerson,"person");
var xml2:XML = objectToXml2(testPerson,"person");
var xml3:XML = objectToXml3(testPerson,"person");
返回结果
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<person email="mail@mail.com" image="ttt.swf" name="xxx" phone="123456" role="leader"/>
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<person>
<email>mail@mail.com</email>
<image>ttt.swf</image>
<name>xxx</name>
<phone>123456</phone>
<role>leader</role>
</person>
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<person>
<email>mail@mail.com</email>
<image>ttt.swf</image>
<name>xxx</name>
<phone>123456</phone>
<role>leader</role>
</person>
另外Adobe也有一个object转xml的例子,有感兴趣的可以参考一下。
http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=11988
你也可以直接在此下载这个示例代码
SimpleSerializer.zip
--kaixuan's cnblogs