actionscript3,XML自動解析器開源咯,
這東西寫出來很久了,自己也用了很長時間,感覺沒什么bug了今天才獨立放出來。
現在開源這么多,什么GUI,tween的都有了,想來想去才想出一個有點新意的東西。隨便取了個名:asMapper。
先上個簡單例子。本例是把一個xml解析為as的類
xml代碼:
<test> <hello>worlds</hello> </test>
新建一個vo類
package { public class TestVO { public var hello:String; } }
主類構造
public var xmlMapper:XmlMapper; public function TestMapper() { var testXML:XML = XML ( <test> <hello>worlds</hello> </test> ); xmlMapper = new XmlMapper(); // 把TestVO類型注冊到mapper里面,給它一個別名test與xml的根節點對應 xmlMapper.regClz(TestVO,"test"); var obj:TestVO = xmlMapper.fromXML(testXML); var xmlStr:* = xmlMapper.toXML(obj); trace(xmlStr); }
打個斷點看看:

與xml同名的屬性解析上去了
-----------------------------------------------------------
這個例子很簡單,如果想解析對象里面又有對象的話,下面上個復雜些的例子。
vo類代碼
package { public class Test2VO { public var helloTest:TestVO; public var helloObj:Object; public var helloLs:Array; } }
主類測試代碼:
private function test2():void { var testXML:XML = XML ( <test2> <helloTest> <hello>worlds</hello> </helloTest> <helloObj> <attr1>1</attr1> <attr2>2</attr2> </helloObj> <helloLs> <String>worlds</String> <int>11</int> <test> <hello>worlds2</hello> </test> <test> <hello>worlds3</hello> </test> </helloLs> </test2> ); xmlMapper = new XmlMapper(); // 把TestVO類型注冊到mapper里面,給它一個別名test與xml的根節點對應 xmlMapper.regClz(TestVO,"test"); xmlMapper.regClz(Test2VO,"test2"); var obj:Test2VO = xmlMapper.fromXML(testXML); var xmlStr:* = xmlMapper.toXML(obj); trace(xmlStr); }
再看看截圖,嘿嘿,解析上去了

------------------------------------------
另外還有一個引用語法的xml語法例子。
引用語法,先上個例子,vo類
package { public class Test3VO { public var test1:TestVO; public var test2:TestVO; } }
斷點看一下,解析成功。

用特效引用字符解析是防止死循環,比如A里面有屬性引用B而B里面又有屬性引用了A,不加方法處理就出錯了。adobe官方的json解析是有這個bug的,大家不防試試。
有個不完美的地方,就是動態對象Object里面的屬性我無法反射出它的屬性的類型.例如<Object><test /></Object>這樣是解析不了的。目前想到的方法只有在節點里面加一屬性來表示類型。如果有高手有更好的方法望跟我聯系。
本解析工具最吃性能的是describeType方法,因為這個反射,所以會多消耗幾十個毫秒。我用了一個LRU緩存池來將反射存內存,所以只會在第一次反射時慢幾十毫秒,第二次之后基本十毫秒之內解析完成…… 不過緩存工具還可能有bug,我並沒有將它正式放出。
代碼包里面有一個json的包,暫時沒時間寫了,現在的項目暫時不用json。真正項目中很多朋友還是用amf,那東西可以用adobe內置方法解析。
SVN地址:https://as-mapper.googlecode.com/svn/trunk/as3Mapper
