to XML from Object via JAXB - Java XML

Java examples for XML:JAXB

Description

to XML from Object via JAXB

Demo Code


//package com.java2s;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        Object obj = "java2s.com";
        System.out.println(toXML(obj));
    }/* w w w  . j  av  a2 s. co m*/

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

Related Tutorials