eagle

          學(xué)無(wú)止境,細(xì)節(jié)決定成敗.
          posts - 12, comments - 11, trackbacks - 0, articles - 2
            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          Jaxb筆記

          Posted on 2012-01-30 14:02 月下孤城 閱讀(3546) 評(píng)論(0)  編輯  收藏

          最近項(xiàng)目原因,研究了下jaxbjaxbJava api xml binding的簡(jiǎn)稱,是為實(shí)現(xiàn)javaxml數(shù)據(jù)的相互轉(zhuǎn)換而定義的一個(gè)api標(biāo)準(zhǔn)。該標(biāo)準(zhǔn)以annotation的方式實(shí)現(xiàn)xml的轉(zhuǎn)換。不用開(kāi)發(fā)人員單獨(dú)解析每個(gè)對(duì)象屬性與xml元素的mapping關(guān)系,只需在java bean中注入簡(jiǎn)單的java annotation,其他的交給工具去處理。該工具包類(lèi)能給xml數(shù)據(jù)處理帶來(lái)極大方便。具體實(shí)現(xiàn)見(jiàn)下。

          Java bean對(duì)象定義:

          /**
           * 促銷(xiāo)xml對(duì)象類(lèi) 
           * 
          @author daiqiang
           * 對(duì)應(yīng)xml文件內(nèi)容如下:
           * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
              <promotion>
                  <id>promotionId</id>
                  <name>元旦促銷(xiāo)</name>
                  <type>CMS</type>
                  <typeDes>CMS主推促銷(xiāo)</typeDes>
                  <startTime>2012-01-01</startTime>
                  <endTime>2012-01-03</endTime>
                  <products>
                      <product>
                          <merchantId>merchantid</merchantId>
                          <num>500</num>
                          <productCode>code1</productCode>
                          <productId>111</productId>
                          <requestId>codedata</requestId>
                      </product>
                      <product>
                          <merchantId>merchantid2</merchantId>
                          <num>800</num>
                          <productCode>code2</productCode>
                          <productId>2</productId>
                          <requestId>codedata</requestId>
                      </product>
                  </products>
              </promotion>
           *
           
          */

          @XmlRootElement(name
          ="promotion")
          @XmlAccessorType(XmlAccessType.FIELD)
          public class Promotion implements Serializable{

              
          private static final long serialVersionUID = 870036805093867083L;
              
              
          private String id;
              
          private String name;
              
          private String type;
              
          private String typeDes;
              
          private String startTime;
              
          private String endTime;
              
              @XmlElementWrapper(name
          ="products")
              @XmlElement(name
          ="product")
              
          private List<Product> products;
              
              
          /*@XmlTransient
              the field is not binded to xml
              private String testHiddenFields;
          */

              
          //此處省略具體set get 方法。

          說(shuō)明:上文定義了一個(gè)促銷(xiāo)對(duì)象類(lèi)Promotion.

          類(lèi)標(biāo)注表示:

          @XmlRootElement:用于定義該對(duì)象映射成xml根節(jié)點(diǎn)元素名,默認(rèn)與類(lèi)名一致。可通過(guò)@XmlRootElement(name="otherRootElement")方式指定具體名稱。

           

          @XmlAccessorType: 用于標(biāo)識(shí)該java對(duì)象與xml映射的訪問(wèn)方式。有如下屬性值。

          PROPERTY/FIELD/PUBLIC_MEMBER/NONE

           

          PROPERTY: 所有set/get方法對(duì)將被映射為xml元素.除非被XmlTransient標(biāo)注例外.

           

          FIELD:所有對(duì)象屬性將被映射為xml元素。除非被XmlTransient標(biāo)注例外.

           

          PUBLIC_MEMBER每個(gè)publicget/set對(duì)方法或public field將被映射為xml元素。除非被XmlTransient標(biāo)注例外.

           

          NONE沒(méi)有fields property被映射,除非顯示指定具體fieldsproperty

           

           

          屬性標(biāo)注表示:

          @XmlTransient:指對(duì)應(yīng)屬性不做xml映射。

          @XmlElement(name="product"):指定屬性映射時(shí)對(duì)應(yīng)xml元素名稱

          @XmlElementWrapper(name="products"):在某些場(chǎng)景下,需要對(duì)映射的屬性做包裝處理。如例子中products List對(duì)象屬性,在xml中我想在映射對(duì)所有的product元素再做一個(gè)products 元素包裝,如下所示,就可以按此種方式實(shí)現(xiàn)。

          <products>

              <product> … </product>

              <product> … </product>

              …

          </products>

           

          Javaxml映射方法

           

          Java對(duì)象到XML

           

          /**
               * convent java object to xml format String.
               * 
               * 
          @param originalObj
               * 
          @param xmlCharset
               *            the format of charset for xml. ie "UTF-8", "GBK"
               * 
          @param isFragment
               *            whether or not display the header for the generated xml. such
               *            as <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
               * 
          @return
               
          */

              
          public static String convertJava2XmlStr(Object originalObj,
                      String xmlCharset, 
          boolean isFragment) {
                  String xmlStr 
          = "";
                  
          try {
                      JAXBContext ctx 
          = JAXBContext.newInstance(originalObj.getClass());
                      Marshaller marshaller 
          = ctx.createMarshaller();
                      marshaller.setProperty(Marshaller.JAXB_ENCODING, xmlCharset);
                      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, 
          true);
                      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, isFragment);

                      ByteArrayOutputStream os 
          = new ByteArrayOutputStream();
                      marshaller.marshal(originalObj, os);

                      xmlStr 
          = os.toString();
                  }
           catch (PropertyException e) {
                      e.printStackTrace();
                  }
           catch (JAXBException e) {
                      e.printStackTrace();
                  }
           catch (Exception e) {
                      e.printStackTrace();
                  }

                  
          return xmlStr;
              }

           

          XMLJava對(duì)象

           

          /**
               * convert xml string to Java object by JAXB.
               * 
          @param obj  to convert java object.
               * 
          @param xmlStr    
               * 
          @return
               
          */

              
          public static Object convertXmlStr2Java(Object obj, String xmlStr) {
                  
          try {
                      JAXBContext ctx 
          = JAXBContext.newInstance(obj.getClass());
                      InputStream source 
          = new ByteArrayInputStream(xmlStr.getBytes());
                      Unmarshaller unmarshaller 
          = ctx.createUnmarshaller();
                      obj 
          = unmarshaller.unmarshal(source);
                  }
           catch (JAXBException e) {
                      e.printStackTrace();
                  }

                  
          return obj;
              }






          ---------------------
          月下孤城
          mail:eagle_daiqiang@sina.com

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 开鲁县| 二连浩特市| 龙陵县| 江陵县| 新和县| 林西县| 峨眉山市| 黄骅市| 县级市| 商都县| 固镇县| 胶州市| 彭泽县| 长乐市| 新建县| 寻乌县| 尤溪县| 方山县| 凌源市| 新营市| 任丘市| 威远县| 乳山市| 天镇县| 太白县| 惠安县| 石嘴山市| 张家界市| 偃师市| 葵青区| 凤凰县| 鹿泉市| 天峨县| 鸡泽县| 大冶市| 台江县| 湾仔区| 西藏| 兰溪市| 万宁市| 喀什市|