Java XML JAXB Marshaller marshallJAXBObject(String namespace, Object o)

Here you can find the source of marshallJAXBObject(String namespace, Object o)

Description

Marshall a JAXB object and return the XML as a string.

License

Mozilla Public License

Declaration

public static String marshallJAXBObject(String namespace, Object o) throws JAXBException 

Method Source Code

//package com.java2s;
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
    private static Map<String, JAXBContext> JAXBContextInstances = new HashMap<String, JAXBContext>();

    /**//  www  .ja  v  a2  s .  c o  m
     * Marshall a JAXB object and return the XML as a string. The XML declaration will be added.
     */
    public static String marshallJAXBObject(String namespace, Object o) throws JAXBException {
        return marshallJAXBObject(namespace, o, true);
    }

    /**
     * Marshall a JAXB object and return the XML as a string
     */
    public static String marshallJAXBObject(String namespace, Object o, boolean addXMLDeclaration)
            throws JAXBException {
        JAXBContext jc = getJAXBContext(namespace);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", addXMLDeclaration);
        StringWriter sw = new StringWriter();
        marshaller.marshal(o, sw);
        return sw.toString();
    }

    public static JAXBContext getJAXBContext(String namespace) throws JAXBException {
        if (!JAXBContextInstances.containsKey(namespace))
            JAXBContextInstances.put(namespace, JAXBContext.newInstance(namespace));
        return JAXBContextInstances.get(namespace);
    }
}

Related

  1. marshall(String cntxtPkg, Object obj, OutputStream out)
  2. marshall(String file, JAXBElement object, Class context)
  3. marshaller(Object o, Class T)
  4. marshaller(Object obj, File file)
  5. marshallerObject(Class c, Object o)
  6. marshallMessage(Object message, Marshaller marshaller, DataOutputStream dos)
  7. marshallObjectAsString(Class clazz, T object)
  8. marshallObjectToXML(final Object jaxbModel, final URL schemaURL)
  9. marshallToString(Object jaxbElement, Class c)