最近写的用于分析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"
{
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"
{
value [name].push (getValue (node.childNodes [i]));
} else
{
value [name].push (getValue (node [i]));
}
} else
{
if (type == "xml"
{
value [name] = getValue (node.childNodes [i]);
} else
{
value [name] = getValue (node [i]);
}
}
} else
{
if (type == "xml"
{
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就是转换出来的对象。