convert Object To XML via JAXB - Android XML

Android examples for XML:JAXB

Description

convert Object To XML via JAXB

Demo Code


//package com.java2s;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object object = "java2s.com";
        System.out.println(convertObjectToXML(object));
    }/*from  w  ww. j a  va2 s .  c o m*/

    public static String convertObjectToXML(Object object) {
        JAXBContext jaxbContext = null;
        Marshaller jaxbMarshaller = null;
        StringWriter stringWriter = new StringWriter();
        try {
            jaxbContext = JAXBContext.newInstance(object.getClass());
            jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    Boolean.TRUE);
            jaxbMarshaller.marshal(object, stringWriter);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        String xmlString = stringWriter.toString();

        return xmlString;

    }
}

Related Tutorials