摘自: http://www.blogjava.net/eagle-daiq/archive/2012/01/30/369016.html

最近项目原因,研究了下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;
    }

Jaxb笔记的更多相关文章

  1. Java学习笔记4

    Java学习笔记4 1. JDK.JRE和JVM分别是什么,区别是什么? 答: ①.JDK 是整个Java的核心,包括了Java运行环境.Java工具和Java基础类库. ②.JRE(Java Run ...

  2. JAXB性能优化

    前言: 之前在查阅jaxb相关资料的同时, 也看到了一些关于性能优化的点. 主要集中于对象和xml互转的过程中, 确实有些实实在在需要注意的点. 这边浅谈jaxb性能优化的一个思路. 案列: 先来构造 ...

  3. Jaxb对xml报文头的小修小改

    前言: 也是在实际工作中, 借助jaxb来实现xml到java对象的映射转换. 在实际应用中, 也遇到了一些有趣好玩的东西, 权当记录下来. 本文主要讲解jaxb如何生成约定的xml报文头的实现思路, ...

  4. 当Jaxb遇到泛型

    前言: 最近的工作内容跟银行有些交互, 对方提供的数据格式采用xml(不是预期的json/protobuf). 为了开发方便, 需要借助jaxb来实现xml和java对象之间的映射. 它还是有点像ja ...

  5. 【Spring学习笔记-MVC-3】SpringMVC返回Json数据-方式1

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  6. SpringMvc 笔记

    整理出来是 SpringMvc 笔记 方便以后查询 框架太多了 不经常使用 忘记的可能性很大 自己整理一套笔记 一看就明白了 1 对比 原始请求响应流程 1 发送请求 --> 2 控制层 --& ...

  7. 1.《Spring学习笔记-MVC》系列文章,讲解返回json数据的文章共有3篇,分别为:

    转自:https://www.cnblogs.com/ssslinppp/p/4528892.html [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://w ...

  8. Spring MVC-学习笔记(3)参数绑定注解、HttpMessageConverter<T>信息转换、jackson、fastjson、XML

    1.参数绑定注解 1>@RequestParam: 用于将指定的请求参数赋值给方法中的指定参数.支持的属性: 2>@PathVariable:可以方便的获得URL中的动态参数,只支持一个属 ...

  9. git-简单流程(学习笔记)

    这是阅读廖雪峰的官方网站的笔记,用于自己以后回看 1.进入项目文件夹 初始化一个Git仓库,使用git init命令. 添加文件到Git仓库,分两步: 第一步,使用命令git add <file ...

随机推荐

  1. window.opener调用父窗体方法的用法

    应用实例:        function BindWindowCloss() {            $(window).bind('beforeunload', function () {    ...

  2. C语言 负数取余的原理

    负数求余数运算是一个数学问题: 任何一个整数n都可以表示成 n=k*q+r 其中0<=|r|<|q| 这里的r就是n除以q的余数,即 r==n%q 例如: -9=(-2)*4+(-1) 则 ...

  3. tyvj 1049 最长不下降子序列 n^2/nlogn

    P1049 最长不下降子序列 时间: 1000ms / 空间: 131072KiB / Java类名: Main 描述 求最长不下降子序列的长度 输入格式 第一行为n,表示n个数第二行n个数 输出格式 ...

  4. ZOJ 1240 IBM Minus One

    /* You may have heard of the book '2001 - A Space Odyssey' by Arthur C. Clarke, or the film of the s ...

  5. Vue.js相关知识3-路由

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  6. [luogu P2170] 选学霸(并查集+dp)

    题目传送门:https://www.luogu.org/problem/show?pid=2170 题目描述 老师想从N名学生中选M人当学霸,但有K对人实力相当,如果实力相当的人中,一部分被选上,另一 ...

  7. centOS 6.x 版本安装 node.js 4.x 以上版本的方法

    由于 node 4.x 以上版本,通过编译源代码来安装,对 GCC 的版本有要求,而 centos 的 GCC 版本不够,更新 GCC 也很麻烦,所以只能通过别的方式解决. 这里主要介绍直接下载编译后 ...

  8. 最长不下降子序列的O(n^2)算法和O(nlogn)算法

    一.简单的O(n^2)的算法 很容易想到用动态规划做.设lis[]用于保存第1~i元素元素中最长不下降序列的长度,则lis[i]=max(lis[j])+1,且num[i]>num[j],i&g ...

  9. 如何给caffe添加新的layer ?

    如何给caffe添加新的layer ? 初学caffe难免会遇到这个问题,网上搜来一段看似经典的话, 但是问题来了,貌似新版的caffe并没有上面提到的vision_layer:

  10. C++ 遇到的问题小结

    1. cannot convert 'std::basic_string<char>' to 'int' in assignment ... 原始code如下: int id2; std: ...