Java XML JAXB Marshaller marshalToString(Object obj)

Here you can find the source of marshalToString(Object obj)

Description

marshal To String

License

Open Source License

Declaration

public static String marshalToString(Object obj) throws JAXBException 

Method Source Code

//package com.java2s;
//## The MIT License

import java.io.StringWriter;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;

public class Main {
    private static ConcurrentHashMap<Class<?>, JAXBContext> contextMap = new ConcurrentHashMap<Class<?>, JAXBContext>();
    private static javax.xml.parsers.DocumentBuilderFactory dbf;

    public static String marshalToString(Object obj) throws JAXBException {
        StringWriter writer = new StringWriter();

        JAXBContext jc = getContext(obj.getClass());
        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(obj, writer);

        return writer.toString();
    }//from  w w w  . j av  a2s.  c  om

    private static JAXBContext getContext(Class<?> c) throws JAXBException {
        JAXBContext jc = contextMap.get(c);
        if (jc == null) {
            jc = JAXBContext.newInstance(c);
            contextMap.put(c, jc);
        }

        return jc;
    }

    public static org.w3c.dom.Element marshal(Object obj) throws JAXBException {
        try {
            Document doc = null;
            JAXBContext jc = getContext(obj.getClass());
            Marshaller marshaller = jc.createMarshaller();
            doc = dbf.newDocumentBuilder().newDocument();
            marshaller.marshal(obj, doc);
            return doc.getDocumentElement();
        } catch (ParserConfigurationException ex) {
            throw new JAXBException("Error in creating document elements: " + ex.getMessage());
        }
    }
}

Related

  1. marshallXml(final Object object)
  2. marshallXMLInConsole(Object obj)
  3. marshalObject(Object obj, File file)
  4. marshalObjectToXml(Object object, String xmlFilePath)
  5. marshalPackage(OutputStream printStream, final Package p)
  6. marshalToString(Object obj)
  7. marshalV2(Class clazz, T obj, String uri, String nodeName)
  8. removeStandalone(final Marshaller marshaller)
  9. setEncoding(@Nonnull final Marshaller aMarshaller, @Nullable final Charset aEncoding)