把XML解析成AS3对象

AS3的原生XML工具还凑合,但是有时候需要把自己定义的XML数据解析成ActionScript3的Object。

废话不说,代码:

Java代码  收藏代码
  1. <span style=”font-size: medium;”>package com.linkage.cmp.serialization.xml{
  2.     /**
  3.      * 静态工具类,将xml对象或者字符串转换成AS3对象。
  4.      * 注意:参数必须是标准单根结构的XML对象或者字符串,如果传递的参数不是合法的XML格式,将会抛出解析异常。
  5.      * @author  章小飞 zhangxf5@asiainfo-linkage.com
  6.      * @since   2011-01-18
  7.      */
  8.     public class XmlParser{
  9.         /**
  10.          * 私有:解析过程中内部使用的堆栈
  11.          */
  12.         private static var stack:Array=[];
  13.         public function XmlParser(){
  14.             throw new Error(“不能实例化工具类XmlParser”);
  15.         }
  16.         public static function parse(obj:*):*{
  17.             var result:Object=null;
  18.             try{
  19.                 if(!obj){
  20.                     return result;
  21.                 }
  22.                 if(!(obj is XML)){
  23.                     obj=new XML(obj.toString());
  24.                 }
  25.                 //清空堆栈
  26.                 stack=[];
  27.                 doParse(obj);
  28.                 result=stack[0];
  29.             }catch(e:Error){
  30.                 throw new Error(“Xml2Obj无法解析所提供的XML数据”);
  31.             }
  32.             return result;
  33.         }
  34.         /**
  35.          * 递归解析,前序遍历
  36.          */
  37.         private static function doParse(root:XML):void{
  38.             var obj:Object={name:root.name().toString(),children:[]};
  39.             stack.push(obj);
  40.             //解析直接属性
  41.             var attrLen:int=root.attributes().length();
  42.             for(var j:int=0;j<attrLen;j++){
  43.                 var attr:XML=root.attributes()[j];
  44.                 obj[attr.name().toString()||"_temp"]=attr.toString();
  45.             }
  46.             //解析子标签
  47.             var len:int=root.children().length();
  48.             if(len){
  49.                 for(var i:int=0;i<len;i++){
  50.                     var sub:XML=root.children()[i];
  51.                     var subLen:int=sub.children().length();
  52.                     if(subLen){
  53.                         doParse(sub);
  54.                         var temp:Object=stack.pop();
  55.                         var temp2:Object=stack[stack.length-1];
  56.                         temp2.children.push(temp);
  57.                     }else{
  58.                         var top:Object=stack[stack.length-1];
  59.                         delete top.children;
  60. //                      top[top.name]=sub.toString();
  61. //                      delete top.name;
  62.                         top.value=sub.toString();
  63.                     }
  64.                 }
  65.             }
  66.         }
  67.     }
  68. }</span>

下面是测试用例:

Java代码  收藏代码
  1. <span style=”font-size: medium;”><?xml version=”1.0″ encoding=”utf-8″?>
  2. <s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″
  3.                xmlns:s=”library://ns.adobe.com/flex/spark”
  4.                xmlns:mx=”library://ns.adobe.com/flex/mx” minWidth=”955″ minHeight=”600″>
  5.     <s:layout>
  6.         <s:BasicLayout/>
  7.     </s:layout>
  8.     <fx:Declarations>
  9.         <!– 将非可视元素(例如服务、值对象)放在此处 –>
  10.     </fx:Declarations>
  11.     <fx:Script>
  12.         <![CDATA[
  13.             import com.linkage.cmp.serialization.json.JSON;
  14.             import com.linkage.cmp.serialization.xml.XmlParser;
  15.             private function test():void{
  16.                 //第一种用法,直接解析XML对象,可以嵌套任意深度
  17.                 var xml:XML=<root>
  18.                                 <name>大漠穷秋</name>
  19.                                 <age>25</age>
  20.                                 <skills>
  21.                                     <skill>AS3</skill>
  22.                                     <skill>C++</skill>
  23.                                     <skill>Java</skill>
  24.                                 </skills>
  25.                             </root>;
  26.                 var obj:Object=XmlParser.parse(xml);
  27.                 trace(JSON.encode(obj));
  28.                 //第二种用法:直接给一个XML字符串
  29.                 var str:String="<root type='001' attr2='002'><node>名称</node></root>";
  30.                 var obj2:Object=XmlParser.parse(str);
  31.                 trace(JSON.encode(obj2));
  32.             }
  33.         ]]>
  34.     </fx:Script>
  35.     <s:Button click=”test()” label=”test”>
  36.     </s:Button>
  37. </s:Application>
  38. </span>

说明:

XmlParser的包声明你自己改吧,应该木有难度。

这是FlashBuilder的工程,如果是Flex3,请自行更改测试代码里面的标签。

示例出来的效果是这样的:

Java代码  收藏代码
  1. <span style=”font-size: medium;”>{“children”:[{"name":"name","value":"大漠穷秋"},{"name":"age","value":"25"},{"children":[{"name":"skill","value":"AS3"},{"name":"skill","value":"C++"},{"name":"skill","value":"Java"}],”name”:”skills”}],”name”:”root”}
  2. {“type”:”001″,”children”:[{"name":"node","value":"名称"}],”name”:”root”,”attr2″:”002″}</span>


发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(Spamcheck Enabled)