天天看點

Java實體類轉xml,利用Marshaller生成xml

不說什麼了,直接上代碼吧!
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;



/**
 * Jaxb工具類 xml和java類互相轉換
 * @author Gxf
 * @date 2020-5-12
 */
public class JaxbXmlUtil {

    public static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * pojo轉換成xml 預設編碼UTF-8
     *
     * @param obj 待轉化的對象
     * @return xml格式字元串
     * @throws Exception JAXBException
     */
    public static String convertToXml(Object obj) throws Exception {
        return convertToXml(obj, DEFAULT_ENCODING);
    }

    /**
     * pojo轉換成xml
     * @param obj 待轉化的對象
     * @param encoding 編碼
     * @return xml格式字元串
     * @throws Exception JAXBException
     */
    public static String convertToXml(Object obj, String encoding) throws Exception {
        String result = null;
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        // 指定是否使用換行和縮排對已編組 XML 資料進行格式化的屬性名稱。
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        result = writer.toString();
        return result;
    }

    /**
     * pojo轉換成xml ,不聲明XML頭部資訊
     *
     * @param obj 待轉化的對象
     * @param encoding 編碼
     * @return xml格式字元串
     * @throws Exception JAXBException
     */
    public static String convertToXmlNoHead(Object obj, String encoding) throws Exception {
        String result = null;
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        // 指定是否使用換行和縮排對已編組 XML 資料進行格式化的屬性名稱。
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT,true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        result = writer.toString();

        return result;
    }


    /**
     * xml轉換成JavaBean
     *
     * @param xml xml格式字元串
     * @param t 待轉化的對象
     * @return 轉化後的對象
     * @throws Exception JAXBException
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertToJavaBean(String xml, Class<T> t) throws Exception {
        T obj = null;
        JAXBContext context = JAXBContext.newInstance(t);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        obj = (T) unmarshaller.unmarshal(new StringReader(xml));
        return obj;
    }
}
           

如果對您有幫助,請點個贊吧!

Java實體類轉xml,利用Marshaller生成xml