Java XML JAXB Object to XML convertObjectToXml(Object object)

Here you can find the source of convertObjectToXml(Object object)

Description

convert Object To Xml

License

Open Source License

Declaration

public static String convertObjectToXml(Object object) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import java.io.StringWriter;

public class Main {
    public static String convertObjectToXml(Object object) throws Exception {
        return convertObjectToXml(object, "UTF-8");
    }//from  w ww. j ava  2  s  . co  m

    public static String convertObjectToXml(Object object, String encoding) throws Exception {

        try {
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

            StringWriter writer = new StringWriter();
            marshaller.marshal(object, writer);

            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("convert object to xml error");
        }
    }
}

Related

  1. asXml(T object)
  2. convertObjectToXML(Object object)
  3. convertToString(Object obj)
  4. convertToXml(Object obj)
  5. convertToXml(Object obj)