返回首頁

將Flash內部的XML轉換成對象的類

時間:2013-03-29 17:00來源:知行網www.wtckvq.live 編輯:麥田守望者

最近寫的用于分析Flash內部XML,并轉換成對象的類.與大家分享.
我用了多次,可以解析較復雜的XML對象.
XmlToArray類代碼如下,請保存為XmlToArray.as:

import mx.events.EventDispatcher;
class XmlToArray
{
private var data : Object, xml : Object;
public var tem_nodes : XML;
function XmlToArray (tn : XML)
{
tem_nodes = tn;
tem_nodes.ignoreWhite = true;
}
function toObject () : Object
{
var data : Object = parse (tem_nodes);
return data;
}
private function parse (node : XMLNode) : Object
{
//var node:XMLNode = tem_nodes;
var value : Object = new Object ();
if (node.childNodes.length != (undefined || null))
{
var nodes : Number = node.childNodes.length;
var type : String = "xml"
} else
{
var temp_array = node;
var nodes : Number = temp_array.length;
var type : String = "array"
}
for (var i = 0; i != nodes; ++ i)
{
if (type == "xml"[img]/images/wink.gif[/img]
{
var name : String = node.childNodes [i].nodeName;
} else
{
var name : String = node [i].nodeName;
}
if (name != null)
{
if (value [name] != undefined)
{
if ( ! (value [name] instanceof Array))
{
value [name] = new Array (value [name]);
}
if (type == "xml"[img]/images/wink.gif[/img]
{
value [name].push (getValue (node.childNodes [i]));
} else
{
value [name].push (getValue (node [i]));
}
} else
{
if (type == "xml"[img]/images/wink.gif[/img]
{
value [name] = getValue (node.childNodes [i]);
} else
{
value [name] = getValue (node [i]);
}
}
} else
{
if (type == "xml"[img]/images/wink.gif[/img]
{
value = getValue (node.childNodes [i]);
} else
{
value = getValue (node [i]);
}

}
}
var attributes : Object = getAttributes (node);
if (attributes != null)
{
if (nodes != 0)
{
if ( ! (value instanceof XMLNode))
{
for (var i in value)
{
attributes [i] = value [i];
}
} else
{
attributes [’_val’] = value.nodeValue;
}
}
return attributes;
}
return value;
}
private function getAttributes (node : XMLNode) : Object
{
var attributes = new Object ();
for (var i in node.attributes)
{
attributes [i] = node.attributes [i];
}
return i != undefined ? attributes : null;
}
private function getValue (node : XMLNode) : Object
{
switch (node.nodeType)
{
case 1 :
return parse (node);
case 3 :
return node.toString ();
}
return null;
}
private function finalize ()
{
delete xml;
}
}

用法:

 

import XmlToArray;
var xml = new XML("<CourseWare><name>AAAAA</name></CourseWare>");
xml.ignoreWhite = true;
var my_xml = new XmlToArray(xml);
var a:Object = my_xml.toObject();
//a就是轉換出來的對象。

------分隔線----------------------------
標簽(Tag):FLASH FLASH實例教程 flash技巧 flash源代碼 flash基礎教程
------分隔線----------------------------
推薦內容
猜你感興趣
深蓝海域APP