Java 怎么通过JAXB从对象到XML

2019年7月21日20:00:14Java 怎么通过JAXB从对象到XML已关闭评论 349 697字阅读2分19秒

1.简介

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

2.示例代码

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



import java.io.StringWriter;
import javax.xml.bind.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object obj = "tah1986.com";
        System.out.println(toXML(obj));
    }

    public static String toXML(Object obj) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.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 out = new StringWriter();
            marshaller.marshal(obj, out);
            return out.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 
编程十万个怎么办