Java XML JAXB Marshaller marshal(T bean, Class... bc)

Here you can find the source of marshal(T bean, Class... bc)

Description

Convert a bean to XML format using JAXB.

License

Open Source License

Parameter

Parameter Description
bean The bean to marshal as XML.
bc Additional classes to register on the JAXB context for marshalling.

Return

An XML representation of the bean.

Declaration

public static <T> String marshal(T bean, Class<?>... bc) 

Method Source Code


//package com.java2s;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import java.io.ByteArrayOutputStream;

public class Main {
    /**/*  w  ww .j  ava  2s  .com*/
     * Convert a bean to XML format using JAXB.
     * 
     * @param bean
     *            The bean to marshal as XML.
     * @param bc
     *            Additional classes to register on the JAXB context for
     *            marshalling.
     * @return An XML representation of the bean.
     */
    public static <T> String marshal(T bean, Class<?>... bc) {
        assert bean != null;
        Class<?>[] bind;
        if (bc.length > 0) {
            bind = new Class<?>[bc.length + 1];
            bind[0] = bean.getClass();
            for (int i = 0; i < bc.length; i++)
                bind[i + 1] = bc[i];
        } else
            bind = new Class<?>[] { bean.getClass(), };
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(bind);
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(bean, baos);
        } catch (JAXBException e) {
            throw new IllegalStateException("Error marshalling", e);
        }
        return new String(baos.toByteArray());
    }
}

Related

  1. marshal(Object object)
  2. marshal(Object object, File file, JAXBContext ctx)
  3. marshal(Object object, OutputStream stream)
  4. marshal(Object objectToMarshal)
  5. marshal(Object source, Class configurationClass)
  6. marshal(T clazz)
  7. marshal(T object)
  8. marshal(T t, Class entityClass)
  9. marshalAsString(Class clz, T marshalObj)