jaxb

近项目原因,研究了下jaxb。jaxb是Java api xml binding的简称,是为实现java与xml数据的相互转换而定义的一个api标准。该标准以annotation的方式实现xml的转换。不用开发人员单独解析每个对象属性与xml元素的mapping关系,只需在java bean中注入简单的java annotation,其他的交给工具去处理。该工具包类能给xml数据处理带来极大方便。具体实现见下。

Java bean对象定义:

/**
 * 促销xml对象类 
 * @author daiqiang
 * 对应xml文件内容如下:
 * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <promotion>
        <id>promotionId</id>
        <name>元旦促销</name>
        <type>CMS</type>
        <typeDes>CMS主推促销</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 方法。

说明:上文定义了一个促销对象类Promotion.

类标注表示:

@XmlRootElement:用于定义该对象映射成xml根节点元素名,默认与类名一致。可通过@XmlRootElement(name="otherRootElement")方式指定具体名称。

 

@XmlAccessorType: 用于标识该java对象与xml映射的访问方式。有如下属性值。

PROPERTY/FIELD/PUBLIC_MEMBER/NONE

 

PROPERTY: 所有set/get方法对将被映射为xml元素.除非被XmlTransient标注例外.

 

FIELD:所有对象属性将被映射为xml元素。除非被XmlTransient标注例外.

 

PUBLIC_MEMBER每个public的get/set对方法或public field将被映射为xml元素。除非被XmlTransient标注例外.

 

NONE没有fields 或 property被映射,除非显示指定具体fields或property。

 

 

属性标注表示:

@XmlTransient:指对应属性不做xml映射。

@XmlElement(name="product"):指定属性映射时对应xml元素名称

@XmlElementWrapper(name="products"):在某些场景下,需要对映射的属性做包装处理。如例子中products List对象属性,在xml中我想在映射对所有的product元素再做一个products 元素包装,如下所示,就可以按此种方式实现。

<products>

    <product> … </product>

    <product> … </product>

    …

</products>

Javaxml映射方法

 

Java对象到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对象

/**
     * 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;
    }
原文地址:https://www.cnblogs.com/xiamengfei/p/4543497.html