??? jibx又一個(gè)不錯(cuò)的xml綁定工具,隨著這段時(shí)間的使用,感覺(jué)越來(lái)越隨心應(yīng)手了。和jaxb一樣,都是屬于xml綁定工具。不同于jaxb,jibx使用java字節(jié)碼enhance技術(shù),而jaxb更多在于源代碼生成技術(shù)。jibx的工作主要在于前期,也就是進(jìn)行字節(jié)碼綁定,這一部分基本上都是在編譯器完成的。在運(yùn)行期,不需要任何的配置,由于字節(jié)碼已經(jīng)嵌入java類(lèi)中。而jaxb更多在于運(yùn)行期綁定,通過(guò)元數(shù)據(jù)或者xsd文件進(jìn)行解析綁定。相對(duì)于jaxb來(lái)說(shuō),jibx更加的快速以及靈活。不過(guò),前期的編譯工作還是需要花費(fèi)一點(diǎn)時(shí)間熟悉。下面通過(guò)一個(gè)簡(jiǎn)單的例子來(lái)說(shuō)明,例子是其官方自帶的。
??? 首先從網(wǎng)上下載jibx包 http://jibx.sourceforge.net/ 為其主要的官網(wǎng)。
??? 假設(shè)有兩個(gè)類(lèi)Person和Customer
??? 使用最簡(jiǎn)單的方式聲明:
??? 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 數(shù)據(jù)結(jié)構(gòu)如下:
<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>
?
為了匹配相應(yīng)的數(shù)據(jù),jibx需要相應(yīng)的映射文檔,用于匹配java類(lèi)和xml數(shù)據(jù),如下:
<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>? ?
?
當(dāng)然手寫(xiě)是比較費(fèi)力的,還好,jibx工具提供了相應(yīng)的生成方法:jibxtools包提供了BindingGenerator類(lèi),用于生成相應(yīng)的xml文件
可以直接在cmd下執(zhí)行:java -jar? jibxtools.jar -f bind.xml Customer
如果沒(méi)有復(fù)雜的屬性,如枚舉和數(shù)組,直接就可以生成了。
現(xiàn)在開(kāi)始編譯期的最后一步:綁定類(lèi)
同樣可以使用cmd的方式或者ant task來(lái)執(zhí)行
java -jar jibx-bind.jar binding.xml
主要的執(zhí)行類(lèi)為org.jibx.binding.Compile,也可以直接運(yùn)行此類(lèi)
如果你有java反編譯器,可以查看相應(yīng)的類(lèi)文件已經(jīng)更改,增加了相應(yīng)的jibx信息,并且增加了相應(yīng)的jibx_binding*_access類(lèi)。
在運(yùn)行期,你只需要使用以下的代碼來(lái)進(jìn)行處理就行了,由于jibx 使用最新的xml pull技術(shù),執(zhí)行的速度還是比較快的。
?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數(shù)據(jù)結(jié)構(gòu)比較固定,可以考慮使用。
posted on 2007-02-26 20:44
布衣郎 閱讀(4352)
評(píng)論(0) 編輯 收藏 所屬分類(lèi):
webservies