Fork me on GitHub
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.com/svn/trunk/as3Mapper

 
分类: 程序人生
标签: as3xml解析mapper
posted on 2012-06-07 20:27  HackerVirus  阅读(1032)  评论(0编辑  收藏  举报