Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import javax.xml.bind.*;
import javax.xml.namespace.QName;

import java.io.StringWriter;

public class Main {

    public static String object2Xml(Object obj) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        StringWriter writer = new StringWriter();
        marshaller.marshal(new JAXBElement(new QName("xml"), obj.getClass(), obj), writer);

        return writer.toString();
    }
}