??? 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
布衣郎 閱讀(4352)
評論(0) 編輯 收藏 所屬分類:
webservies