最近写的用于分析Flash内部XML,并转换成对象的类.与大家分享.
我用了多次,可以解析较复杂的XML对象.
XmlToArray类代码如下,请保存为XmlToArray.as:
importmx.events.EventDispatcher;
classXmlToArray
{
privatevardata:Object,xml:Object;
publicvartem_nodes:XML;
functionXmlToArray(tn:XML)
{
tem_nodes=tn;
tem_nodes.ignoreWhite=true;
}
functiontoObject():Object
{
vardata:Object=parse(tem_nodes);
returndata;
}
privatefunctionparse(node:XMLNode):Object
{
//varnode:XMLNode=tem_nodes;
varvalue:Object=newObject();
if(node.childNodes.length!=(undefined||null))
{
varnodes:Number=node.childNodes.length;
vartype:String="xml"
}else
{
vartemp_array=node;
varnodes:Number=temp_array.length;
vartype:String="array"
}
for(vari=0;i!=nodes;++i)
{
if(type=="xml"
{
varname:String=node.childNodes[i].nodeName;
}else
{
varname:String=node[i].nodeName;
}
if(name!=null)
{
if(value[name]!=undefined)
{
if(!(value[name]instanceofArray))
{
value[name]=newArray(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]);
}
}
}
varattributes:Object=getAttributes(node);
if(attributes!=null)
{
if(nodes!=0)
{
if(!(valueinstanceofXMLNode))
{
for(variinvalue)
{
attributes[i]=value[i];
}
}else
{
attributes[’_val’]=value.nodeValue;
}
}
returnattributes;
}
returnvalue;
}
privatefunctiongetAttributes(node:XMLNode):Object
{
varattributes=newObject();
for(variinnode.attributes)
{
attributes[i]=node.attributes[i];
}
returni!=undefined?attributes:null;
}
privatefunctiongetValue(node:XMLNode):Object
{
switch(node.nodeType)
{
case1:
returnparse(node);
case3:
returnnode.toString();
}
returnnull;
}
privatefunctionfinalize()
{
deletexml;
}
}
用法:
importXmlToArray;
varxml=newXML("<CourseWare><name>AAAAA</name></CourseWare>");
xml.ignoreWhite=true;
varmy_xml=newXmlToArray(xml);
vara:Object=my_xml.toObject();
//a就是转换出来的对象。