Flex3 Object to xml

//自己遍历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;
}

 

 

调用方示
var testPerson:Object = {name:"xxx",role:"leader",phone:"123456",email:"[email protected]",image:"ttt.swf"};
var xml1:XML = objectToXml1(testPerson,"person");
var xml2:XML = objectToXml2(testPerson,"person");
var xml3:XML = objectToXml3(testPerson,"person");

 

返回结果

xml1的值
<person email="[email protected]" image="ttt.swf" name="xxx" phone="123456" role="leader"/>

 

xml2的值
<person>
  
<email>[email protected]</email>
  
<image>ttt.swf</image>
  
<name>xxx</name>
  
<phone>123456</phone>
  
<role>leader</role>
</person>

 

xml3的值
<person>
  
<email>[email protected]</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

你可能感兴趣的:(职场,Flex3,休闲,ObjectToXml)