关于java对象转xml格式的util类

package com.xd;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.w3c.dom.Node;
/***
 * jbx实例
 * @author yang
 *
 */
@SuppressWarnings("all")
public class JAXBUtils {
/**
     * 获取JAXBContext实例。
     * @param clazz
     * @return
     */
    private static final JAXBContext getJAXBContext(Class<?> c){
        JAXBContext jaxbContext=null;
        try {
            jaxbContext = JAXBContext.newInstance(c);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return jaxbContext;
    }


    /**
     * 将报文节点反序列化为实体类
     * @param obj
     * @param node
     * @return
     */
    public static final Object documentToModel(Object obj,Node node){
        if(node == null){
            return null;
        }
        JAXBContext jaxbContext = getJAXBContext(obj.getClass());
        try {
            //得到反序列化实例Unmarshaller
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            obj= unmarshaller.unmarshal(node);
        } catch (JAXBException e) {
            e.printStackTrace();
        }


        return obj;
    }


    /**
     * 将实体类转序列化为对应String类型xml节点
     * @param obj
     * @return
     */
    public static final String modelToStringXML(Object obj){
        StringWriter writer= new StringWriter();
        JAXBContext jaxbContext = getJAXBContext(obj.getClass());
        try {
            Marshaller marshaller = jaxbContext.createMarshaller();
    //设置序列化的编码格式    
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    //设置格式化输出   
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(obj, writer);
        } catch (JAXBException e) {
            e.printStackTrace();
        }


        return writer.toString();


    }






    /**
     * 将实体类转序列化为对应node节点
     * @param obj   实体类
     * @param node  创建的新节点
     * @return
     */
    public static final Node modelToNode(Object obj,Node node){
        JAXBContext jaxbContext = getJAXBContext(obj.getClass());
        try {
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(obj, node);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return node;


    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值