Java 怎么通过JAXB从对象获取XML

2019年7月21日20:01:49Java 怎么通过JAXB从对象获取XML已关闭评论 416 1129字阅读3分45秒

1.简介

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

2.示例代码

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


import java.io.ByteArrayOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;

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

    public static String getXMLFromObject(Object objJAXB) throws Exception {
        return marshal(objJAXB);
    }

    private static String marshal(Object objJAXB) throws Exception {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        newMarshaller(objJAXB.getClass()).marshal(objJAXB,
                newWriter(result));
        return result.toString();
    }

    private static Marshaller newMarshaller(Class<?> classJAXB)
            throws Exception {
        return newContext(classJAXB).createMarshaller();
    }

    private static XMLStreamWriter newWriter(ByteArrayOutputStream result)
            throws Exception {
        XMLOutputFactory output = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = output.createXMLStreamWriter(result);
        return writer;
    }

    private static JAXBContext newContext(Class<?> classJAXB)
            throws Exception {
        return JAXBContext.newInstance(classJAXB);
    }
}

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