Java XML JAXB Marshaller marshall(final Object o, Class clazz)

Here you can find the source of marshall(final Object o, Class clazz)

Description

Marshalls the given JaxB class into a XML document while explicitly providing the class

License

Apache License

Parameter

Parameter Description
o The JaxB object instance
clazz The class of the object which shall be marshalled

Declaration

public static String marshall(final Object o, Class<?> clazz) 

Method Source Code

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

import java.io.PrintWriter;

import java.io.StringWriter;

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

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Main {
    private static final Logger logger = LogManager.getRootLogger();

    /**//from  w w w .  jav a2 s . co m
     * Marshalls the given JaxB class into a XML document while explicitly providing the class
     * @param o The JaxB object instance
     * @param clazz The class of the object which shall be marshalled
     * @return 
     */
    public static String marshall(final Object o, Class<?> clazz) {
        Marshaller m;
        try {
            m = JAXBContext.newInstance(clazz).createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            final StringWriter w = new StringWriter();
            m.marshal(o, w);
            return w.toString();
        } catch (JAXBException e) {
            StringWriter trace = new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            logger.warn("text" + System.getProperty("line.separator") + trace.toString());
        }
        return null;
    }

    /**
     * Marshalls the given JaxB class into a XML document
     * @param o The JaxB object instance
     * @return 
     */
    public static String marshall(final Object o) {
        return marshall(o, o.getClass());
    }
}

Related

  1. marshal(T clazz)
  2. marshal(T object)
  3. marshal(T t, Class entityClass)
  4. marshalAsString(Class clz, T marshalObj)
  5. marshall(Class c, String xml)
  6. marshall(Object o)
  7. marshall(Object obj)
  8. marshall(Object obj, URL schemaURL, Class... classesToBeBound)
  9. marshall(Object toMarshall)