XMANcharles
12/1/2017 - 2:08 AM

XML2J

XML和JavaObject之间的转换

/*
 * Copyright (C), 1995-2017, 没钱有限公司
 * FileName: Xml2J
 * Author:   Neo Geng
 * Date:     2017/10/25 10:41
 * Description: XMl to JavaObject
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.cubwolf.serializable2j;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;

/**
 * 〈XML to JavaObject〉
 * <p>T-必须实现Serializable接口,并且使用 {@link javax.xml.bind.annotation.XmlRootElement} </p>
 * @author Neo Geng
 *         Date 2017/10/25
 * @since 1.0.0
 */
public class Xml2JUtil {

    private Xml2JUtil(){

    }

    /**
     * XMl文件转换object
     * @param clazz 泛型类对象
     * @param filePath xml文件路径
     * @param <T> 泛型
     * @return T
     */
    public static <T extends Serializable> T convertXml2Obj(Class<T> clazz, String filePath){
        try {
            //Jaxb上下文
            JAXBContext context = JAXBContext.newInstance(clazz);
            //解排器
            Unmarshaller unmarshaller = context.createUnmarshaller();
            //解排-
            return (T) unmarshaller.unmarshal(new File(filePath));
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Object转XMl文件
     * @param t 对象
     * @param filePath 保存的xml文件路径
     * @param <T>
     */
    public static <T extends Serializable> void convertObj2Xml(T t,String filePath){
        try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8")){
            //JAXB上下文
            JAXBContext context = JAXBContext.newInstance(t.getClass());
            //编排器
            Marshaller marshaller = context.createMarshaller();
            //编排参数-格式化输出
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
            //编排
            marshaller.marshal(t,outputStreamWriter);
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 对象转换成XMlString
     * @param t
     * @param <T>
     * @return
     */
    public static <T extends Serializable> String convertObj2Xmlstr(T t){
        StringWriter writer = new StringWriter();
        try {
            //Jaxb上下文
            JAXBContext context = JAXBContext.newInstance(t.getClass());
            //编排器
            Marshaller marshaller = context.createMarshaller();
            //编排格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
            //编排
            marshaller.marshal(t,writer);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return writer.toString();
    }


}