JAVA Pojo转换为Xml字符串 工具类

package com.idc.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class XmlUtil {

    /**
     * pojo 转换为 XMl 字符串
     * @param obj
     * @return
     * @throws JAXBException
     */
    public static String convertToXml(Object obj) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        return writer.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39706515/article/details/130732140