码迷,mamicode.com
首页 > 编程语言 > 详细

Java操作XML的工具:JAXB

时间:2017-08-30 15:49:24      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:ade   属性   main   工具类   注解   gen   center   word   fragment   

Java Architecture for XML Binding (JAXB) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到XML实例文档。从另一方面来讲,JAXB提供了快速而简便的方法将XML模式绑定到Java表示,从而使得Java开发者在Java应用程序中能方便地结合XML数据和处理函数。

这意味着你不需要处理甚至不需要知道XML编程技巧就能在Java应用程序中利用平台核心XML数据的灵活性。而且,可以充分利用XML的优势而不用依赖于复杂的XML处理模型如SAX或DOM。JAXB 隐藏了细节并且取消了SAX和DOM中没用的关系——生成的JAXB类仅描述原始模型中定义的关系。其结果是结合了高度可移植Java代码和高度可移植的XML数据。其中这些代码可用来创建灵活、轻便的应用程序和Web服务。     JAXB(java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到 XML实例文档。  Jaxb 2.0是JDK 1.6的组成部分。我们不需要下载第三方jar包 即可做到轻松转换。Jaxb2使用了JDK的新特性,如:Annotation、GenericType等,需要在即将转换的JavaBean中添加annotation注解。

 

一、重要概念

  • JAXBContext类,是应用的入口,用于管理XML/Java绑定信息。
  • Marshaller接口,将Java对象序列化为XML数据。
  • Unmarshaller接口,将XML数据反序列化为Java对象。
  • @XmlType,将Java类或枚举类型映射到XML模式类型
  • @XmlAccessorType(XmlAccessType.FIELD) ,控制字段或属性的序列化。FIELD表示JAXB将自动绑定Java类中的每个非静态的(static)、非瞬态的(由@XmlTransient标 注)字段到XML。其他值还有XmlAccessType.PROPERTY和XmlAccessType.NONE。
  • @XmlAccessorOrder,控制JAXB 绑定类中属性和字段的排序。
  • @XmlJavaTypeAdapter,使用定制的适配器(即扩展抽象类XmlAdapter并覆盖marshal()和unmarshal()方法),以序列化Java类为XML。
  • @XmlElementWrapper ,对于数组或集合(即包含多个元素的成员变量),生成一个包装该数组或集合的XML元素(称为包装器)。
  • @XmlRootElement,将Java类或枚举类型映射到XML元素。
  • @XmlElement,将Java类的一个属性映射到与属性同名的一个XML元素。
  • @XmlAttribute,将Java类的一个属性映射到与属性同名的一个XML属性。

二、工具类

package com.ehaoyao.jobcenter.order.webservices.jztdzy.Util;

import org.apache.poi.ss.formula.functions.T;

import javax.xml.bind.*;
import javax.xml.namespace.QName;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

public class JAXBUtil {

    /**
     * beanToXml
     * @param obj
     * @param encoding
     * @return
     */
    public static String toXml(Object obj,String encoding) {
        try {
            StringWriter sw = new StringWriter();
            JAXBContext context = JAXBCache.instance().getJAXBContext(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xm头声明信息
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            marshaller.marshal(obj, sw);
            return sw.toString().replace("ns2:","").replace(":ns2","");
        } catch(JAXBException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    /**
     * xmlToBean
     * @param xml
     * @param c
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T toBean(String xml, Class<T> c,String encoding) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
}

  

package com.ehaoyao.jobcenter.order.webservices.jztdzy.Util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
public final class JAXBCache {
    private static final JAXBCache instance = new JAXBCache();
    private final ConcurrentMap<String, JAXBContext> contextCache = new ConcurrentHashMap<String, JAXBContext>();
    private JAXBCache() {
    }
    public static JAXBCache instance() {
        return instance;
    }
    JAXBContext getJAXBContext(Class<?> clazz) throws JAXBException {
        JAXBContext context = contextCache.get(clazz.getName());
        if ( context == null )
        {
            context = JAXBContext.newInstance(clazz);
            contextCache.putIfAbsent(clazz.getName(), context);
        }
        return context;
    }
}

  

package com.ehaoyao.jobcenter.order.webservices.jztdzy.Util;

public class XMLNameSpace {
    public static final String ADMIN_PREFIX = "";
    public static final String ADMIN_URI = "http://WebServices.WS.JointownTech.com//";
}

  

package com.ehaoyao.jobcenter.order.webservices.jztdzy.Util;

import com.ehaoyao.jobcenter.order.webservices.jztdzy.model.ElecPrescription;
import com.thoughtworks.xstream.annotations.XStreamAlias;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Created by wls on 2017/8/15.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder= {"result","errorDesc","elecPrescription"})
public class AddPrescriptionToMes2ItemResponse {
//    @XStreamAlias("result")
    @XmlElement(name="result",namespace = XMLNameSpace.ADMIN_URI)
    private String result;
    @XmlElement(required = false)
    private String errorDesc;
    @XmlElement(required = false)
    private ElecPrescription elecPrescription;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getErrorDesc() {
        return errorDesc;
    }

    public void setErrorDesc(String errorDesc) {
        this.errorDesc = errorDesc;
    }

    public ElecPrescription getElecPrescription() {
        return elecPrescription;
    }

    public void setElecPrescription(ElecPrescription elecPrescription) {
        this.elecPrescription = elecPrescription;
    }

    @Override
    public String toString() {
        return "AddPrescriptionToMes2ItemResponse{" +
            "result=‘" + result + ‘\‘‘ +
            ", errorDesc=‘" + errorDesc + ‘\‘‘ +
            ", elecPrescription=" + elecPrescription +
            ‘}‘;
    }
}

  

package com.ehaoyao.jobcenter.order.webservices.jztdzy.Util;

import com.thoughtworks.xstream.annotations.XStreamAlias;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 * Created by wls on 2017/8/15.
 */
//@XStreamAlias("string")
@XmlRootElement(name = "string",namespace = XMLNameSpace.ADMIN_URI)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder= {"response"})
public class AddPrescriptionToMes2Response {
    @XmlElement(name = "response",namespace = XMLNameSpace.ADMIN_URI)
    private AddPrescriptionToMes2ItemResponse response;

    public AddPrescriptionToMes2ItemResponse getResponse() {
        return response;
    }

    public void setResponse(AddPrescriptionToMes2ItemResponse response) {
        this.response = response;
    }

    @Override
    public String toString() {
        return "AddPrescriptionToMes2Response{" +
            "response=" + response +
            ‘}‘;
    }
}

  

package com.ehaoyao.jobcenter.order.webservices.jztdzy.Util;

import com.ehaoyao.jobcenter.order.webservices.jztdzy.model.ElecPrescription;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Created by wls on 2017/8/17.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder= {"result","errorDesc"},namespace = XMLNameSpace.ADMIN_URI)
public class SetWXPrescriptionInfoItemResponse {
    @XmlElement(name = "result",namespace = XMLNameSpace.ADMIN_URI)
    private ElecPrescription result;
    private String errorDesc;


    public ElecPrescription getResult() {
        return result;
    }

    public void setResult(ElecPrescription result) {
        this.result = result;
    }

    public String getErrorDesc() {
        return errorDesc;
    }

    public void setErrorDesc(String errorDesc) {
        this.errorDesc = errorDesc;
    }

}

  

package com.ehaoyao.jobcenter.order.webservices.jztdzy.Util;

import com.thoughtworks.xstream.annotations.XStreamAlias;

import javax.xml.bind.annotation.*;

/**
 * Created by wls on 2017/8/17.
 */
//@XStreamAlias("string")
@XmlRootElement(name = "string",namespace = XMLNameSpace.ADMIN_URI)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder= {"response"})
public class SetWXPrescriptionInfoResponse {
    @XmlElement(name = "response",namespace = XMLNameSpace.ADMIN_URI)
    private SetWXPrescriptionInfoItemResponse response;

    public SetWXPrescriptionInfoItemResponse getResponse() {
        return response;
    }

    public void setResponse(SetWXPrescriptionInfoItemResponse response) {
        this.response = response;
    }
}

  三、测试类

package com.ehaoyao.jobcenter.test;

import com.alibaba.fastjson.JSONObject;
import com.ehaoyao.jobcenter.order.webservices.jztdzy.Util.AddPrescriptionToMes2Response;
import com.ehaoyao.jobcenter.order.webservices.jztdzy.Util.JAXBUtil;
import com.ehaoyao.jobcenter.order.webservices.jztdzy.Util.SetWXPrescriptionInfoResponse;
import com.ehaoyao.jobcenter.order.webservices.jztdzy.model.ElecPrescription;
import org.apache.poi.ss.formula.functions.T;

import static org.junit.Assert.*;

public class JaxbUtilTest {

    public static void main(String[] args) {
        ElecPrescription elecPrescription = new ElecPrescription();
        elecPrescription.setAddress("测试地址");
        elecPrescription.setAge(12);
        elecPrescription.setAgentNum(1);
        elecPrescription.setBillDates("2017-08-19 12:02:21");
        elecPrescription.setBlank2("1");
        elecPrescription.setBlank3("1");
        elecPrescription.setBusinessId("1435");
        String ret = JAXBUtil.toXml(elecPrescription,"UTF-8");
        System.out.println(ret);
        elecPrescription = (ElecPrescription) JAXBUtil.toBean(ret,ElecPrescription.class,"UTF-8");
        System.out.println(elecPrescription);

        ret = "<string xmlns=\"http://WebServices.WS.JointownTech.com//\"><response><result>1</result></response></string>";
        AddPrescriptionToMes2Response addPrescriptionToMes2Response = JAXBUtil.toBean(ret,AddPrescriptionToMes2Response.class,"UTF-8");
        System.out.println(addPrescriptionToMes2Response!=null? JSONObject.toJSONString(addPrescriptionToMes2Response):null);

        ret = "<string xmlns=\"http://WebServices.WS.JointownTech.com//\"><response><result><BillDates>2017-08-16</BillDates><OutPrescriptionCode>100004</OutPrescriptionCode><OutPrescriptionSn>1004</OutPrescriptionSn><tpyq>代煎</tpyq><zgyq></zgyq><Patient>张三</Patient><Gender>女</Gender><Age>12</Age><CFDates>2017-08-17</CFDates><IsPregnancy>否</IsPregnancy><cflx>外用</cflx><AgentNum>1</AgentNum><Remark></Remark><Opinion></Opinion><BusinessName>好药师三方渠道</BusinessName><orgname>湖北公司</orgname><Dosages>1</Dosages><jyyq>1</jyyq><jyfa>微压(密闭)解表(15min)</jyfa><PatientCode></PatientCode><PictureIP>http://10.2.72.200:131/DCIM/010100003639731150</PictureIP><GoodsDatas><GoodsData><GoodsName>炒蒺藜</GoodsName><Dosage>1</Dosage><GoodsTpyq>无</GoodsTpyq><InvoiceP>0</InvoiceP></GoodsData></GoodsDatas><LogisticsCost>0</LogisticsCost><ProcessingCost>0</ProcessingCost><cfzt>作废</cfzt><cfjd><CFREVIEWSTAFF></CFREVIEWSTAFF><CFREVIEWTIME></CFREVIEWTIME><MIXSTAFF></MIXSTAFF><MIXREQUESTTIME></MIXREQUESTTIME><MIXSURETIME></MIXSURETIME><MIXREVIEWSTAFF></MIXREVIEWSTAFF><MIXREVIEWTIME></MIXREVIEWTIME><SOAKSTAFF></SOAKSTAFF><SOAKREQUESTTIME></SOAKREQUESTTIME><SOAKSURETIME></SOAKSURETIME><TISANESTAFF></TISANESTAFF><TISANEREQUESTTIME></TISANEREQUESTTIME><TISANESURETIME></TISANESURETIME>  <OINTMENTSTAFF></OINTMENTSTAFF><OINTMENTREQUESTTIME></OINTMENTREQUESTTIME><OINTMENTSURETIME></OINTMENTSURETIME><INNERPACKINGSTAFF></INNERPACKINGSTAFF><INNERPACKINGTIME></INNERPACKINGTIME><OUTERPACKINGSTAFF>zyadmin</OUTERPACKINGSTAFF><OUTERPACKINGTIME>2017-08-16 16:41:56</OUTERPACKINGTIME></cfjd><psjd><LogisticsCompany></LogisticsCompany><ExpressNumber></ExpressNumber></psjd></result></response></string>";
        SetWXPrescriptionInfoResponse setWXPrescriptionInfoResponse = JAXBUtil.toBean(ret,SetWXPrescriptionInfoResponse.class,"UTF-8");
        System.out.println(setWXPrescriptionInfoResponse!=null? JSONObject.toJSONString(setWXPrescriptionInfoResponse):null);
    }
}
}

  

 

  四、运行效果

  技术分享

 

Java操作XML的工具:JAXB

标签:ade   属性   main   工具类   注解   gen   center   word   fragment   

原文地址:http://www.cnblogs.com/wlsblog/p/7452882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!