Flex:没有SimpleXMLEncoder的ArrayCollection到XML转换

时间:2010-08-20 13:21:54

标签: xml flex function recursion arraycollection

以下是我的转换功能:

private function arrCol2XML(arrCol:ArrayCollection):XML
{
 var xml:XML=new XML(<root></root>);
 for (var i:Number=0; i<arrCol.length; i++)
 {
  var obj:Object=arrCol.getItemAt(i);
  xml.appendChild(recursive(obj));
 }
 return xml;
}

private function recursive(obj:Object, str:String='item'):XML
{
 var xml:XML=new XML('<' + str + '></' + str + '>' );
 if(obj is Array)
 {
  for (var tmpObj:Object in obj)
  {
   Alert.show(flash.utils.getQualifiedClassName(tmpObj) + " - " + str);
//   xml.appendChild(recursive(tmpObj as Object, 'item'));
  }
 } else {
  for (var property:String in obj)
  {
   if(obj[property] is Array)
   {
    xml.appendChild(recursive(obj[property] as Array, property));
   } else {
    xml.appendChild(XML("<" + property + ">" + obj[property].toString() + "</" + property + ">"));
   }
  }
 }
 return xml;
}

以下是我打电话给他们的方式:

Alert.show(arrCol2XML(acRoute).toXMLString());

这里是我的ArrayCollection:

objBlocat = {title:"Blocate", type:"nivel_blocat", children:[
{ title:"alege departament", type:"alege_departament", raspuns:'aaaa'}
]};
acRoute = new ArrayCollection([objIesire, objBlocat]);

我在当前功能状态下的输出是:

<root>
  <item>
    <type>nivel_blocat</type>
    <children/>
    <mx_internal_uid>32F045BF-24B8-8AA8-3E8D-8F9BF92A0AFC</mx_internal_uid>
    <title>Blocate</title>
  </item>
</root>

警报:

int - children

问题:如何解决这个问题,API中是否存在错误?

PS:我承认代码不是直截了当的,因为它根本不起作用。 PPS:如果我的对象具有引用其他对象的属性值,SimpleXMLEncoder会抛出堆栈溢出...这就是为什么我想编写自己的转换方法 任何帮助将非常感谢!非常感谢!

1 个答案:

答案 0 :(得分:0)

使用this作为recursion()来解决它:

private function recursive(obj:Object, str:String='item'):XML
{
    var xml:XML=new XML('<' + str + '></' + str + '>' );
    if(obj is Array && obj.length!=0)
    {
        var ac:ArrayCollection=new ArrayCollection(obj as Array);
        var xml2:XML=new XML(<item></item>);
        for (var i:Number=0; i<ac.length; i++)
        {
            var myObj:Object=ac.getItemAt(i);
            for (var prop:String in myObj)
            {
                xml2.appendChild(new XML("<" + prop + ">" + myObj[prop]  + "</" + prop + ">"));
            }
        }
        xml.appendChild(xml2);
    } else {
        for (var property:String in obj)
        {
            if(obj[property] is Array)
            {
                xml.appendChild(recursive(obj[property] as Array, property));
            } else {
                xml.appendChild(XML("<" + property + ">" + obj[property].toString() + "</" + property + ">"));
            }
        }
    }
    return xml;
}