Java XML JAXB Object to XML toXml(Object o, OutputStream output)

Here you can find the source of toXml(Object o, OutputStream output)

Description

to Xml

License

Apache License

Declaration

public static void toXml(Object o, OutputStream output) 

Method Source Code

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

import java.io.ByteArrayOutputStream;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

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

public class Main {
    public static final String CHARSET = "UTF-8";

    public static void toXml(Object o, OutputStream output) {
        try {//  w ww. j a v  a  2 s  .  com
            JAXBContext context = JAXBContext.newInstance(o.getClass());
            Marshaller marshaller = context.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_ENCODING, CHARSET);
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(o, new OutputStreamWriter(output, CHARSET));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    public static String toXml(Object o) {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            toXml(o, output);
            output.flush();
            return output.toString(CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}

Related

  1. toXml(Class className, Object object)
  2. toXML(final Object obj, final boolean prettyPrint)
  3. toXml(final T dto)
  4. toXML(Object o)
  5. toXML(Object o, OutputStream os)
  6. toXml(Object obj)
  7. toXml(Object object)
  8. toXML(Object thing)
  9. toXml(T element)