Convert object To XML by JAXB - Java XML

Java examples for XML:JAXB

Description

Convert object To XML by JAXB

Demo Code


//package com.java2s;

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 = "java2s.com";
        System.out.println(objectToXML(clazz, object));
    }/*from   ww w . j a v  a  2s.  co  m*/

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

Related Tutorials