pojo To XML via JAXB - Java XML

Java examples for XML:JAXB

Description

pojo To XML via JAXB

Demo Code


//package com.java2s;

import java.io.StringWriter;
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 cla = String.class;
        System.out.println(pojoToXML(cla));
    }/*from  w  w  w .j a va 2s  .  c  o  m*/

    public static String pojoToXML(Class<?> cla) {
        try {
            JAXBContext context = JAXBContext.newInstance(cla.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 writer = new StringWriter();
            marshaller.marshal(cla, writer);
            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related Tutorials