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

2019年7月21日19:58:40Java 怎么通过JAXB将对象转换为XML已关闭评论 515 965字阅读3分13秒

1.简介

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

2.示例代码

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



import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
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 {
        Object object = "tah1986.com";
        System.out.println(convertToXML(object));
    }

    private static Map<Class<?>, Marshaller> mMap = new HashMap<Class<?>, Marshaller>();

    
    public static String convertToXML(Object object) {
        try {
            if (!mMap.containsKey(object.getClass())) {
                JAXBContext jaxbContext = JAXBContext.newInstance(object
                        .getClass());
                Marshaller marshaller = jaxbContext.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                        true);
                mMap.put(object.getClass(), marshaller);
            }
            StringWriter stringWriter = new StringWriter();
            mMap.get(object.getClass()).marshal(object, stringWriter);
            return stringWriter.getBuffer().toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }
}

 
继续阅读
编程十万个怎么办