<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                前面有介紹過json-lib這個框架,在線博文:[http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html](http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html) 以及Jackson這個框架,在線博文:[http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html](http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html) 它們都可以完成Java對象到XML的轉換,但是還不是那么的完善。 還有XStream對JSON及XML的支持,它可以對JSON或XML的完美轉換。在線博文: [http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html](http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html) 以及介紹Castor來完成Java對象到xml的相互轉換。在線博文:[http://www.cnblogs.com/hoojo/archive/2011/04/25/2026819.html](http://www.cnblogs.com/hoojo/archive/2011/04/25/2026819.html) Jaxb2完成xml的轉換,在線博文:[http://www.cnblogs.com/hoojo/archive/2011/04/26/2029011.html](http://www.cnblogs.com/hoojo/archive/2011/04/26/2029011.html) Jibx對Java對象的轉換相對要負責些,它不僅需要配置xml還且還要生成相應的jar文件,已經xsd文件。下面我們就來慢慢看看Jibx轉換Java到XML是如何完成的。 ### 一、準備工作 1、 準備資源 a) 官方示例:[http://jibx.sourceforge.net/fromcode/bindgen-examples.html](http://jibx.sourceforge.net/fromcode/bindgen-examples.html) [http://www.java2s.com/Open-Source/Java/XML/JiBX/tutorial/Catalogtutorial.htm](http://www.java2s.com/Open-Source/Java/XML/JiBX/tutorial/Catalogtutorial.htm) b) Jar下載:[http://sourceforge.net/projects/jibx/files/](http://sourceforge.net/projects/jibx/files/) c) 依賴jar包如下: [![clip_image002](https://box.kancloud.cn/2016-04-15_57105c48a8b13.gif "clip_image002")](http://hi.csdn.net/attachment/201104/27/0_1303875308wJ6L.gif) 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 http://blog.csdn.net/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; @Before public 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(); } } @After public 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到Java 1、 轉換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、setter @Override public String toString() { return this.id + "#" + this.name + "#" + this.email + "#" + this.address + "#" + this.birthday; } } ~~~ Birthday ~~~ package com.hoo.entity; public class Birthday { private String birthday; public Birthday(String birthday) { super(); this.birthday = birthday; } //getter、setter public Birthday() {} @Override public String toString() { return this.birthday; } } ~~~ b) 程序代碼 ~~~ @Test public 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:/Study/WebHttpUtils>java -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 ~~~ <?xml version="1.0" encoding="UTF-8"?> <binding value-style="attribute"> <mapping class="com.hoo.entity.Account" name="account"> <value name="id" field="id"/> <value style="element" name="name" field="name" usage="optional"/> <value style="element" name="email" field="email" usage="optional"/> <value style="element" name="address" field="address" usage="optional"/> <structure field="birthday" usage="optional" name="birthday"> <value style="element" name="birthday" field="birthday" usage="optional"/> </structure> </mapping> </binding> ~~~ entity.xsd文件 ~~~ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://hoo.com/entity" elementFormDefault="qualified" targetNamespace="http://hoo.com/entity"> <xs:element type="tns:account" name="account"/> <xs:complexType name="account"> <xs:sequence> <xs:element type="xs:string" name="name" minOccurs="0"/> <xs:element type="xs:string" name="email" minOccurs="0"/> <xs:element type="xs:string" name="address" minOccurs="0"/> <xs:element name="birthday" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="birthday" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute type="xs:int" use="required" name="id"/> </xs:complexType> </xs:schema> ~~~ 上面最重要的就是bind.xml文件了,下面編譯的時候需要這個文件。Xsd文件可以根據這個文件的內容生成Java的Entity類代碼。 執行完命令后,沒有錯誤就可以運行下面一段命令了。運行命令: E:/Study/WebHttpUtils>java -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xml -v是綁定文件的名稱 運行后,有如下結果: [![clip_image004](https://box.kancloud.cn/2016-04-15_57105c48bd1a2.gif "clip_image004")](http://hi.csdn.net/attachment/201104/27/0_1303875324YYOR.gif) d) 然后你就可以運行上面的Java的Junit測試程序了,運行后結果如下: ~~~ <?xml version="1.0" encoding="UTF-8"?> <account xmlns="http://hoo.com/entity" id="1"> <name>jack</name> <email>email</email> <address>北京</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </account> 1#jack#email#北京#2010-11-22 ~~~ 你還可以用命令來查看某個已經生成bind、schema文件的信息,如: java -cp bin;lib/jibx-run.jar org.jibx.runtime.PrintInfo -c com.hoo.entity.Account 結果如下: [![clip_image006](https://box.kancloud.cn/2016-04-15_57105c48d1cc7.gif "clip_image006")](http://hi.csdn.net/attachment/201104/27/0_13038753307lF2.gif) e) 注意,有時候會出現異常信息,如:java.lang.NoSuchFieldException: JiBX_bindingXXXX就要重復下面的命令就可以了。 java -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xml 2、 轉換帶List集合屬性的JavaBean a) 程序代碼 ~~~ @Test public void listBean2XML() { try { ListBean listBean = new ListBean(); List list = new ArrayList(); list.add(bean); bean = new Account(); bean.setAddress("china"); bean.setEmail("tom@125.com"); 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 輸出: [![clip_image008](https://box.kancloud.cn/2016-04-15_57105c48e3c5d.gif "clip_image008")](http://hi.csdn.net/attachment/201104/27/0_1303875331rAMa.gif) d) 執行完后會生產bind.xml Bind文件 ~~~ <?xml version="1.0" encoding="UTF-8"?> <binding value-style="attribute"> <mapping class="com.hoo.entity.ListBean" name="list-bean"> <value style="element" name="name" field="name" usage="optional"/> <collection field="list" usage="optional" factory="org.jibx.runtime.Utility.arrayListFactory"/> </mapping> </binding> ~~~ e) 運行Compile工具類 在運行前,一定要將最先前運行的Account那個類的bind.xml文件的內容加入到現在這個bind.xml中,因為ListBean依賴了Account這個類。 命令如下: java -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xml 運行后你可以看到最后出現這個 [![clip_image010](https://box.kancloud.cn/2016-04-15_57105c49055c7.gif "clip_image010")](http://hi.csdn.net/attachment/201104/27/0_130387533372oI.gif) f) 運行Test程序,結果如下: ~~~ <?xml version="1.0" encoding="UTF-8"?> <list-bean> <account id="1"> <name>jack</name> <email>email</email> <address>北京</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </account> <account id="2"> <name>tom</name> <email>tom@125.com</email> <address>china</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </account> </list-bean> 1#jack#email#北京#2010-11-22 2#tom#tom@125.com#china#2010-11-22 ~~~ 3、 轉換Java對象數組 a) Test程序 ~~~ /** * function:轉換對象數組 * @author hoojo * @createDate 2011-4-26 下午05:32:03 */ @Test public void arrayBean2XML() { try { Account[] acc = new Account[2]; acc[0] = bean; bean = new Account(); bean.setName("tom"); bean.setId(223); acc[1] = 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個類 [![clip_image012](https://box.kancloud.cn/2016-04-15_57105c4919059.gif "clip_image012")](http://hi.csdn.net/attachment/201104/27/0_1303875335gyP4.gif) d) 運行Compile命令 java -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xml e) 執行完后,就可以運行Test程序了,結果如下 ~~~ <?xml version="1.0" encoding="UTF-8"?> <account-array size="0"> <account id="1"> <name>jack</name> <email>email</email> <address>北京</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </account> <account id="223"> <name>tom</name> </account> </account-array> 1#jack#email#北京#2010-11-22 223#tom#null#null#null ~~~ 4、 轉換帶Map結合的JavaEntity對象 a) Test代碼 ~~~ /** * function:轉換Map集合 * @author hoojo * @createDate 2011-4-26 下午05:40:34 */ @Test public void mapBean2XML() { try { MapBean mapBean = new MapBean(); HashMap map = new HashMap(); map.put("No1", bean); bean = new Account(); bean.setAddress("china"); bean.setEmail("tom@125.com"); 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:/Study/WebHttpUtils>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.MapBean 運行后,會生產bind.xml;修改bind.xml內容如下: ~~~ <?xml version="1.0" encoding="UTF-8"?> <binding value-style="attribute"> <mapping class="com.hoo.entity.Account" name="account"> <value name="id" field="id" /> <value style="element" name="name" field="name" usage="optional" /> <value style="element" name="email" field="email" usage="optional" /> <value style="element" name="address" field="address" usage="optional" /> <structure field="birthday" usage="optional" name="birthday"> <value style="element" name="birthday" field="birthday" usage="optional" /> </structure> </mapping> <mapping class="com.hoo.entity.MapBean" name="map-bean"> <structure field="map" usage="optional" name="map" marshaller="com.hoo.util.HashMapper" unmarshaller="com.hoo.util.HashMapper"> </structure> </mapping> </binding> ~~~ 注意上面的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:http://www.java2s.com/Open-Source/Java/XML/JiBX/tutorial/example21/HashMapper.java.htm * @file HashMapper.java * @package com.hoo.util * @project WebHttpUtils * @blog http://blog.csdn.net/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(m_uri, m_name); } /* (non-Javadoc) * @see org.jibx.runtime.IUnmarshaller#unmarshal(java.lang.Object, * org.jibx.runtime.IUnmarshallingContext) */ public Object unmarshal(Object obj, IUnmarshallingContext ictx) throws JiBXException { // make sure we're at the appropriate start tag UnmarshallingContext ctx = (UnmarshallingContext)ictx; if (!ctx.isAt(m_uri, m_name)) { ctx.throwStartTagNameError(m_uri, m_name); } // create new hashmap if needed int size = ctx.attributeInt(m_uri, SIZE_ATTRIBUTE_NAME, DEFAULT_SIZE); HashMap map = (HashMap)obj; if (map == null) { map = new HashMap(size); } // process all entries present in document ctx.parsePastStartTag(m_uri, m_name); while (ctx.isAt(m_uri, ENTRY_ELEMENT_NAME)) { Object key = ctx.attributeText(m_uri, KEY_ATTRIBUTE_NAME, null); ctx.parsePastStartTag(m_uri, ENTRY_ELEMENT_NAME); Object value = ctx.unmarshalElement(); map.put(key, value); ctx.parsePastEndTag(m_uri, ENTRY_ELEMENT_NAME); } ctx.parsePastEndTag(m_uri, m_name); return map; } public boolean isExtension(String arg0) { return false; } } ~~~ e) 然后運行Compile命令 E:/Study/WebHttpUtils>java -cp bin;lib/jibx-bind.jar org.jibx.binding.Compile -v bind.xml f) 結果如下 ~~~ <?xml version="1.0" encoding="UTF-8"?> <map-bean> <map size="2"> <entry key="No2"> <account id="2"> <name>tom</name> <email>tom@125.com</email> <address>china</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </account> </entry> <entry key="No1"> <account id="1"> <name>jack</name> <email>email</email> <address>北京</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </account> </entry> </map> </map-bean> {No2=2#tom#tom@125.com#china#2010-11-22, No1=1#jack#email#北京#2010-11-22} 1#jack#email#北京#2010-11-22 2#tom#tom@125.com#china#2010-11-22 ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看