Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.Reader;

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

public class Main {
    private static final String prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

    public static String bean2Xml(Object bean) throws Exception {
        StringWriter writer = null;
        try {
            JAXBContext jc = JAXBContext.newInstance(new Class[] { bean.getClass() });
            Marshaller m = jc.createMarshaller();

            m.setProperty("jaxb.fragment", Boolean.valueOf(true));
            writer = new StringWriter();
            m.marshal(bean, writer);
            return prefix + writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(writer);
        }
        return null;
    }

    private static void close(Writer writer) {
        try {
            if (writer == null)
                return;
            writer.close();
        } catch (Exception localException) {
        }
    }

    private static void close(Reader reader) {
        try {
            if (reader == null)
                return;
            reader.close();
        } catch (Exception localException) {
        }
    }
}