Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;

import javax.xml.namespace.QName;

public class Main {
    public static String parseBeanToXmlStringByJAXB(Object bean, Class clase) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(clase);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
        JAXBElement<Object> rootElement = new JAXBElement<Object>(new QName(clase.getSimpleName()), clase, bean);

        OutputStream output = new OutputStream() {

            private StringBuilder string = new StringBuilder();

            public void write(int b) throws IOException {
                this.string.append((char) b);
            }

            //Netbeans IDE automatically overrides this toString()
            public String toString() {
                return this.string.toString();
            }
        };

        marshaller.marshal(rootElement, output);

        return output.toString();

    }
}