




已阅读5页,还剩15页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Jibx完成Java对象和XML相互转换前面有介绍过json-lib这个框架,在线博文:/hoojo/archive/2011/04/21/2023805.html以及Jackson这个框架,在线博文:/hoojo/archive/2011/04/22/2024628.html它们都可以完成Java对象到XML的转换,但是还不是那么的完善。还有XStream对JSON及XML的支持,它可以对JSON或XML的完美转换。在线博文:/hoojo/archive/2011/04/22/2025197.html以及介绍Castor来完成Java对象到xml的相互转换。在线博文:/hoojo/archive/2011/04/25/2026819.htmlJaxb2完成xml的转换,在线博文:/hoojo/archive/2011/04/26/2029011.htmlJibx对Java对象的转换相对要负责些,它不仅需要配置xml还且还要生成相应的jar文件,已经xsd文件。下面我们就来慢慢看看Jibx转换Java到XML是如何完成的。一、 准备工作1、 准备资源a) 官方示例:/fromcode/bindgen-examples.html/Open-Source/Java/XML/JiBX/tutorial/Catalogtutorial.htmb) Jar下载:/projects/jibx/files/c) 依赖jar包如下:2、 程序准备代码package com.hoo.test;import java.io.IOException;import java.io.StringReader;import java.io.StringWriter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import org.jibx.runtime.BindingDirectory;import org.jibx.runtime.IBindingFactory;import org.jibx.runtime.IMarshallingContext;import org.jibx.runtime.IUnmarshallingContext;import org.jibx.runtime.JiBXException;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.hoo.entity.Account;import com.hoo.entity.AccountArray;import com.hoo.entity.Birthday;import com.hoo.entity.ListBean;import com.hoo.entity.MapBean;/* * function: Jibx转换Java到XML * author hoojo * createDate 2011-4-25 下午06:47:33 * file JibxTest.java * package com.hoo.test * project WebHttpUtils * blog /IBM_hoojo * email hoojo_126.com * version 1.0 */public class JibxTest private IBindingFactory factory = null;private StringWriter writer = null;private StringReader reader = null;private Account bean = null;Beforepublic void init() bean = new Account();bean.setAddress(北京);bean.setEmail(email);bean.setId(1);bean.setName(jack);Birthday day = new Birthday();day.setBirthday(2010-11-22);bean.setBirthday(day);try factory = BindingDirectory.getFactory(Account.class); catch (JiBXException e) e.printStackTrace();Afterpublic void destory() bean = null;try if (writer != null) writer.flush();writer.close();if (reader != null) reader.close(); catch (IOException e) e.printStackTrace();System.gc();public void fail(Object o) System.out.println(o);public void failRed(Object o) System.err.println(o);IBindingFactory是一个工厂接口,通过BindingDirectory的getFactory工厂方法可以获得某个对象。然后通过这个工程可以获得转换xml文档的上下文。二、 转换Java到XML、转换XML到Java1、 转换JavaEntity对象a) 首先看看Account、Birthday的代码package com.hoo.entity;public class Account private int id;private String name;private String email;private String address;private Birthday birthday; /getter、setterOverridepublic String toString() return this.id + # + + # + this.email + # + this.address + # + this.birthday;Birthdaypackage com.hoo.entity;public class Birthday private String birthday;public Birthday(String birthday) super();this.birthday = birthday; /getter、setterpublic Birthday() Overridepublic String toString() return this.birthday;b) 程序代码Testpublic void bean2XML() try writer = new StringWriter();/ marshal 编组IMarshallingContext mctx = factory.createMarshallingContext();mctx.setIndent(2);mctx.marshalDocument(bean, UTF-8, null, writer);fail(writer);reader = new StringReader(writer.toString();/unmarshal 解组IUnmarshallingContext uctx = factory.createUnmarshallingContext();Account acc = (Account) uctx.unmarshalDocument(reader, null);fail(acc); catch (Exception e) e.printStackTrace();通过工厂可以获得解组、编组的上下文接口,通过接口可以完成对象的编组、解组。但这样还不够,复杂的东西还在后面。Jibx转换XML文档还要经过一系列复杂的程序。c) 首先,要写bind.xml和schema。不过还好,官方有提高工具类可以用。org.jibx.binding.generator.BindGen或org.jibx.binding.BindingGenerator这两个类都可以,用法如下:首先用dos进入当前工程目录,然后执行命令:E:StudyWebHttpUtilsjava -cp bin;lib/jibx-tools.jar;lib/log4j-1.2.16.jar org.jibx.binding.generator.BindGen -b bind.xml com.hoo.entity.Account上面的java 是运行某个程序 cp是依赖的classpath路径的jar、zip等文件,-b 是输出文件名称,是BindGen类的参数。这样会在当前工程目录中生成bind.xml和entity.xsd文件。先看看这2个文件bind.xml entity.xsd文件 上面最重要的就是bind.xml文件了,下面编译的时候需要这个文件。Xsd文件可以根据这个文件的内容生成Java的Entity类代码。执行完命令后,没有错误就可以运行下面一段命令了。运行命令:E:StudyWebHttpUtilsjava -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xml-v是绑定文件的名称运行后,有如下结果:d) 然后你就可以运行上面的Java的Junit测试程序了,运行后结果如下: jack email 北京 2010-11-22 1#jack#email#北京#2010-11-22你还可以用命令来查看某个已经生成bind、schema文件的信息,如:java -cp bin;lib/jibx-run.jar org.jibx.runtime.PrintInfo -c com.hoo.entity.Account结果如下:e) 注意,有时候会出现异常信息,如:java.lang.NoSuchFieldException: JiBX_bindingXXXX就要重复下面的命令就可以了。java -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xml2、 转换带List集合属性的JavaBeana) 程序代码Testpublic void listBean2XML() try ListBean listBean = new ListBean();List list = new ArrayList();list.add(bean);bean = new Account();bean.setAddress(china);bean.setEmail();bean.setId(2);bean.setName(tom);Birthday day = new Birthday(2010-11-22);bean.setBirthday(day);list.add(bean);listBean.setList(list);writer = new StringWriter();factory = BindingDirectory.getFactory(ListBean.class);/ marshal 编组IMarshallingContext mctx = factory.createMarshallingContext();mctx.setIndent(2);mctx.marshalDocument(listBean, UTF-8, null, writer);fail(writer);reader = new StringReader(writer.toString();/unmarshal 解组IUnmarshallingContext uctx = factory.createUnmarshallingContext();listBean = (ListBean) uctx.unmarshalDocument(reader, null);fail(listBean.getList().get(0);fail(listBean.getList().get(1); catch (Exception e) e.printStackTrace();b) ListBean代码package com.hoo.entity;import java.util.List;public class ListBean private String name;private List list;c) 生成bind.xml执行dos命令:java -cp bin;lib/jibx-tools.jar;lib/log4j-1.2.16.jar org.jibx.binding.BindingGenerator -f bind.xml com.hoo.entity.ListBean输出:d) 执行完后会生产bind.xml Bind文件 e) 运行Compile工具类在运行前,一定要将最先前运行的Account那个类的bind.xml文件的内容加入到现在这个bind.xml中,因为ListBean依赖了Account这个类。命令如下:java -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xml运行后你可以看到最后出现这个f) 运行Test程序,结果如下: jack email 北京 2010-11-22 tom china 2010-11-22 1#jack#email#北京#2010-11-222#tom##china#2010-11-223、 转换Java对象数组a) Test程序/* * function:转换对象数组 * author hoojo * createDate 2011-4-26 下午05:32:03 */Testpublic void arrayBean2XML() try Account acc = new Account2;acc0 = bean;bean = new Account();bean.setName(tom);bean.setId(223);acc1 = bean;AccountArray array = new AccountArray();array.setAccounts(acc);writer = new StringWriter();factory = BindingDirectory.getFactory(AccountArray.class);/ marshal 编组IMarshallingContext mctx = factory.createMarshallingContext();mctx.setIndent(2);mctx.marshalDocument(array, UTF-8, null, writer);fail(writer);reader = new StringReader(writer.toString();/unmarshal 解组IUnmarshallingContext uctx = factory.createUnmarshallingContext();array = (AccountArray) uctx.unmarshalDocument(reader, null);fail(array.getAccounts()0);fail(array.getAccounts()1); catch (Exception e) e.printStackTrace();b) AccountArray代码package com.hoo.entity;public class AccountArray private Account accounts;private int size;public int getSize() size = accounts.length;return size;public void setSize(int size) this.size = size;public Account getAccounts() return accounts;public void setAccounts(Account accounts) this.accounts = accounts;c) 运行命令生成bind.xml文件命令如下:java -cp bin;lib/jibx-tools.jar;lib/log4j-1.2.16.jar org.jibx.binding.BindingGenerator -f bind.xml com.hoo.entity.Account com.hoo.entity.AccountArray因为AccountArray依赖Account,所以后面带2个类d) 运行Compile命令java -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xmle) 执行完后,就可以运行Test程序了,结果如下 jack email 北京 2010-11-22 tom 1#jack#email#北京#2010-11-22223#tom#null#null#null4、 转换带Map结合的JavaEntity对象a) Test代码/* * function:转换Map集合 * author hoojo * createDate 2011-4-26 下午05:40:34 */Testpublic void mapBean2XML() try MapBean mapBean = new MapBean();HashMap map = new HashMap();map.put(No1, bean);bean = new Account();bean.setAddress(china);bean.setEmail();bean.setId(2);bean.setName(tom);Birthday day = new Birthday(2010-11-22);bean.setBirthday(day);map.put(No2, bean);mapBean.setMap(map);factory = BindingDirectory.getFactory(MapBean.class);writer = new StringWriter();/ marshal 编组IMarshallingContext mctx = factory.createMarshallingContext();mctx.setIndent(2);mctx.marshalDocument(mapBean, UTF-8, null, writer);fail(writer);reader = new StringReader(writer.toString();/unmarshal 解组IUnmarshallingContext uctx = factory.createUnmarshallingContext();mapBean = (MapBean) uctx.unmarshalDocument(reader, null);fail(mapBean.getMap();fail(mapBean.getMap().get(No1);fail(mapBean.getMap().get(No2); catch (Exception e) e.printStackTrace();b) MapBean代码package com.hoo.entity;import java.util.HashMap;public class MapBean private HashMap map;public HashMap getMap() return map;public void setMap(HashMap map) this.map = map;c) 生成bind.xml,命令如下E:StudyWebHttpUtilsjava -cp bin;lib/jibx-tools.jar;lib/log4j-1.2.16.jar org.jibx.binding.BindingGenerator -f bind.xml com.hoo.entity.Account com.hoo.entity.MapBean运行后,会生产bind.xml;修改bind.xml内容如下:注意上面的MapBean的structure元素的内容是经过修改的。一定要带上marshaller或unmarshaller,不然无法转换HashMap的。d) HashMapper代码package com.hoo.util;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.jibx.runtime.IAliasable;import org.jibx.runtime.IMarshallable;import org.jibx.runtime.IMarshaller;import org.jibx.runtime.IMarshallingContext;import org.jibx.runtime.IUnmarshaller;import org.jibx.runtime.IUnmarshallingContext;import org.jibx.runtime.JiBXException;import org.jibx.runtime.impl.MarshallingContext;import org.jibx.runtime.impl.UnmarshallingContext;/* * function:/Open-Source/Java/XML/JiBX/tutorial/example21/HashMapper.java.htm * file HashMapper.java * package com.hoo.util * project WebHttpUtils * blog /IBM_hoojo * email hoojo_126.com * version 1.0 */public class HashMapper implements IMarshaller, IUnmarshaller, IAliasable private static final String SIZE_ATTRIBUTE_NAME = size; private static final String ENTRY_ELEMENT_NAME = entry; private static final String KEY_ATTRIBUTE_NAME = key; private static final int DEFAULT_SIZE = 10; private String m_uri; private int m_index; private String m_name; public HashMapper() m_uri = null; m_index = 0; m_name = hashmap; public HashMapper(String uri, int index, String name) m_uri = uri; m_index = index; m_name = name; /* (non-Javadoc) * see org.jibx.runtime.IMarshaller#isExtension(int) */ public boolean isExtension(int index) return false; /* (non-Javadoc) * see org.jibx.runtime.IMarshaller#marshal(java.lang.Object, * org.jibx.runtime.IMarshallingContext) */ public void marshal(Object obj, IMarshallingContext ictx) throws JiBXException / make sure the parameters are as expected if (!(obj instanceof HashMap) throw new JiBXException(Invalid object type for marshaller); else if (!(ictx instanceof MarshallingContext) throw new JiBXException(Invalid object type for marshaller); else / start by generating start tag for container MarshallingContext ctx = (MarshallingContext)ictx; HashMap map = (HashMap)obj; ctx.startTagAttributes(m_index, m_name). attribute(m_index, SIZE_ATTRIBUTE_NAME, map.size(). closeStartContent(); / loop through all entries in hashmap Iterator iter = map.entrySet().iterator(); while (iter.hasNext() Map.Entry entry = (Map.Entry)iter.next(); ctx.startTagAttributes(m_index, ENTRY_ELEMENT_NAME); if (entry.getKey() != null) ctx.attribute(m_index, KEY_ATTRIBUTE_NAME, entry.getKey().toString(); ctx.closeStartContent(); if (entry.getValue() instanceof IMarshallable) (IMarshallable)entry.getValue().marshal(ctx); ctx.endTag(m_index, ENTRY_ELEMENT_NAME); else throw new JiBXException(Mapped value is not marshallable); / finish with end tag for container element ctx.endTag(m_index, m_name); /* (non-Javadoc) * see org.jibx.runtime.IUnmarshaller#isPresent(org.jibx.runtime.IUnmarshallingContext) */ public boolean isPresent(IUnmarshallingContext ctx) throws JiBXException return ctx.isAt
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025抵押借款合同协议模板
- 2025合作伙伴合同转让协议
- 汽修店雇工合同范本
- 遗失补签合同范本
- 装修顶房合同范本
- 2025电影特效制作服务合同
- 小区翻新清洗合同范本
- 配件合作合同范本
- 经委房屋出售合同范本
- 欠款个人担保合同范本
- 巡察整改工作课件模板
- 2025年事业单位工勤技能-河南-河南农机驾驶维修工一级(高级技师)历年参考题库含答案解析(5套)
- 医务人员职业道德准则理论试题
- 2025年幼儿园教师岗位聘任协议(含资格认证及薪酬激励)
- 成都东部集团有限公司招聘考试真题2024
- 银行收息管理办法
- 海外房产投资项目方案(3篇)
- 初中地理学科课程规划方案
- 定额〔2025〕1号文-关于发布2018版电力建设工程概预算定额2024年度价格水平调整的通知
- 《一次函数的图像》-完整版课件
- 电子束曝光机说明书
评论
0/150
提交评论