Java 怎么通过JAXB从POJO到XML

2019年7月21日19:59:44Java 怎么通过JAXB从POJO到XML已关闭评论 430 800字阅读2分40秒

1.简介

Java 怎么通过JAXB从POJO到XML?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



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

public class Main {
    public static void main(String[] argv) throws Exception {
        Class cla = String.class;
        System.out.println(pojoToXML(cla));
    }

    public static String pojoToXML(Class<?> cla) {
        try {
            JAXBContext context = JAXBContext.newInstance(cla.getClass());
            Marshaller marshaller = context.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
            StringWriter writer = new StringWriter();
            marshaller.marshal(cla, writer);
            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }
}

 
编程十万个怎么办