XML自动解析器开源
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测试数据/svn/trunk/as3Mapper
分类: 程序人生
标签: as3 , xml , 解析 , mapper
作者: Leo_wl
出处: http://HdhCmsTestcnblogs测试数据/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息