Java XML JAXB Marshaller marshal(Object obj)

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

Description

marshal

License

Open Source License

Declaration

public static org.w3c.dom.Element marshal(Object obj) throws JAXBException 

Method Source Code

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

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 org.w3c.dom.Element marshal(Object obj) throws JAXBException {
        try {/*w  w  w .  j  av  a2 s . c om*/
            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());
        }
    }

    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;
    }
}

Related

  1. marshal(Marshaller marshaller, Object object, String filename)
  2. marshal(Object bean)
  3. marshal(Object entity)
  4. marshal(Object obj)
  5. marshal(Object obj)
  6. marshal(Object obj, Class clazz)
  7. marshal(Object obj, OutputStream out)
  8. marshal(Object obj, OutputStream out, Class... boundClasses)
  9. marshal(Object obj, OutputStream stream)