Java 怎么通过JAXB将对象转换为XML

2019年7月22日22:34:52Java 怎么通过JAXB将对象转换为XML已关闭评论 280 700字阅读2分20秒

1.简介

Java 怎么通过JAXB将对象转换为XML?——请看下文。

2.示例代码

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



import java.io.StringWriter;
import java.io.Writer;
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 clazz = String.class;
        Object object = "tah1986.com";
        System.out.println(objectToXML(clazz, object));
    }

    public static String objectToXML(Class clazz, Object object)
            throws JAXBException {
        String xml = null;
        JAXBContext context = JAXBContext.newInstance(clazz);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        Writer w = new StringWriter();
        m.marshal(object, w);
        xml = w.toString();
        return xml;
    }
}

 
编程十万个怎么办