闲人野居
好好学习,天天向上
posts - 57,  comments - 137,  trackbacks - 0

    jibx又一个不错的xml绑定工具,随着这段时间的使用,感觉越来越随心应手了。和jaxb一样,都是属于xml绑定工具。不同于jaxb,jibx使用java字节码enhance技术,而jaxb更多在于源代码生成技术。jibx的工作主要在于前期,也就是进行字节码绑定,这一部分基本上都是在编译器完成的。在运行期,不需要任何的配置,由于字节码已经嵌入java类中。而jaxb更多在于运行期绑定,通过元数据或者xsd文件进行解析绑定。相对于jaxb来说,jibx更加的快速以及灵活。不过,前期的编译工作还是需要花费一点时间熟悉。下面通过一个简单的例子来说明,例子是其官方自带的。
    首先从网上下载jibx包 http://jibx.sourceforge.net/ 为其主要的官网。
    假设有两个类Person和Customer
    使用最简单的方式声明:
    public class Customer {
    public Person person;
    public String street;
    public String city;
    public String state;
    public Integer zip;
    public String phone;
   }
    public class Person {
    public int customerNumber;
    public String firstName;
    public String lastName;
   }

xml 数据结构如下:
<customer>
  <person>
    <cust-num>123456789</cust-num>
    <first-name>John</first-name>
    <last-name>Smith</last-name>
  </person>
  <street>12345 Happy Lane</street>
  <city>Plunk</city>
  <state>WA</state>
  <zip>98059</zip>
  <phone>888.555.1234</phone>
</customer>
 
为了匹配相应的数据,jibx需要相应的映射文档,用于匹配java类和xml数据,如下:
<binding>
  <mapping name="customer" class="org.jibx.starter.Customer">
    <structure name="person" field="person">
      <value name="cust-num" field="customerNumber"/>
      <value name="first-name" field="firstName"/>
      <value name="last-name" field="lastName"/>
    </structure>
    <value name="street" field="street"/>
    <value name="city" field="city"/>
    <value name="state" field="state"/>
    <value name="zip" field="zip"/>
    <value name="phone" field="phone"/>
  </mapping>
</binding>   
 
当然手写是比较费力的,还好,jibx工具提供了相应的生成方法:jibxtools包提供了BindingGenerator类,用于生成相应的xml文件
可以直接在cmd下执行:java -jar  jibxtools.jar -f bind.xml Customer
如果没有复杂的属性,如枚举和数组,直接就可以生成了。
现在开始编译期的最后一步:绑定类
同样可以使用cmd的方式或者ant task来执行
java -jar jibx-bind.jar binding.xml
主要的执行类为org.jibx.binding.Compile,也可以直接运行此类
如果你有java反编译器,可以查看相应的类文件已经更改,增加了相应的jibx信息,并且增加了相应的jibx_binding*_access类。
在运行期,你只需要使用以下的代码来进行处理就行了,由于jibx 使用最新的xml pull技术,执行的速度还是比较快的。
 IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
 // unmarshal customer information from file
 IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
 FileInputStream in = new FileInputStream("data.xml");
 Customer customer = (Customer)uctx.unmarshalDocument(in, null);
//marshal
IMarshallingContext mctx = bfact.createMarshallingContext();
mctx.setIndent(2);
FileOutputStream out = new FileOutputStream("data.xml");
mctx.marshalDocument(customer, "UTF-8", null, out);

如果你的xml数据结构比较固定,可以考虑使用。

posted on 2007-02-26 20:44 布衣郎 阅读(4336) 评论(0)  编辑  收藏 所属分类: webservies

只有注册用户登录后才能发表评论。


网站导航:
 

<2007年2月>
28293031123
45678910
11121314151617
18192021222324
25262728123
45678910

常用链接

留言簿(12)

随笔分类(59)

随笔档案(57)

blog

java

uml

搜索

  •  

积分与排名

  • 积分 - 355592
  • 排名 - 154

最新评论

阅读排行榜

评论排行榜