Java XML JAXB Marshaller marshal(JAXBElement jaxbElement, Class cls)

Here you can find the source of marshal(JAXBElement jaxbElement, Class cls)

Description

marshal

License

LGPL

Declaration

public static <T> Element marshal(JAXBElement<T> jaxbElement, Class<T> cls) 

Method Source Code

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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
    public static <T> Element marshal(JAXBElement<T> jaxbElement, Class<T> cls) {
        try {/* ww  w .j  a va2  s  . com*/
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();

            JAXBContext jaxbContext = JAXBContext.newInstance(cls);
            Marshaller marshaller = jaxbContext.createMarshaller();

            marshaller.marshal(jaxbElement, doc);

            return doc.getDocumentElement();
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    /**
     * Converting DOM Element object into JAXB OASIS XML Object
     * @param <T>
     * @param cls
     * @param domElement
     * @return
     */
    public static <T> T marshal(Class<T> cls, Element domElement) {
        try {
            JAXBContext jc = JAXBContext.newInstance(cls);
            javax.xml.bind.Unmarshaller unmarshaller = jc.createUnmarshaller();
            JAXBElement<T> jaxbObject = unmarshaller.unmarshal(domElement, cls);

            T object = jaxbObject.getValue();

            return object;
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. marshal(final Object obj, final Class... classes)
  2. marshal(final Object object)
  3. marshal(final Object object)
  4. marshal(JAXBContext context, Object object, Writer writer, Map properties)
  5. marshal(JAXBElement e, File f)
  6. marshal(JAXBElement value, String contextPath, OutputStream out, ClassLoader classLoader)
  7. marshal(Marshaller m, File out, Object o)
  8. marshal(Marshaller marshaller, Object object, String filename)
  9. marshal(Marshaller marshaller, Object object, String filename)