marshal Object to XML String using JAXB - Java XML

Java examples for XML:JAXB

Description

marshal Object to XML String using JAXB

Demo Code


//package com.java2s;
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 = "java2s.com";
        System.out.println(marshal(objJAXB));
    }//from   ww  w  .j  a v  a 2 s. com

    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);
    }
}

Related Tutorials