Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.Serializable;

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

import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
    /**
     * Helper method to serialize an object to XML. Requires object to be Serializable
     * @param entity Object to serialize
     * @param <T> class that implements Serializable
     * @return String XML representation of object
     * @throws IOException if errors during serialization
     * @throws JAXBException if errors during serialization
     */
    public static <T extends Serializable> String getXml(T entity) throws IOException, JAXBException {
        StringWriter sw = new StringWriter();

        if (null != entity) {
            JAXBContext ctx = JAXBContext.newInstance(entity.getClass());

            Marshaller m = ctx.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            m.marshal(entity, sw);
        }
        sw.flush();
        sw.close();

        return sw.toString();
    }
}