Java XML JAXB Marshaller marshal(Class c, String xml)

Here you can find the source of marshal(Class c, String xml)

Description

marshal

License

Open Source License

Parameter

Parameter Description
T the type we want to convert the XML into
c the class of the parameterized type
xml the instance XML description

Exception

Parameter Description
JAXBException an exception

Return

a deserialization of the XML into an object of type T of class class

Declaration

public static <T> T marshal(Class<T> c, String xml) throws JAXBException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Main {
    /**// w  w w  .j av a 2s . c o m
     * @param <T> the type we want to convert the XML into
     * @param c the class of the parameterized type
     * @param xml the instance XML description
     * @return a deserialization of the XML into an object of type T of class class <T>
     * @throws JAXBException
     */
    public static <T> T marshal(Class<T> c, String xml) throws JAXBException {
        T res;

        if (c == xml.getClass()) {
            res = (T) xml;
        } else {
            JAXBContext ctx = JAXBContext.newInstance(c);
            Unmarshaller marshaller = ctx.createUnmarshaller();
            res = (T) marshaller.unmarshal(new StringReader(xml));
        }

        return res;
    }

    /**
     * @param <T> the type to serialize
     * @param c the class of the type to serialize
     * @param o the instance containing the data to serialize
     * @return a string representation of the data.
     * @throws Exception
     */
    public static <T> String unmarshal(Class<T> c, Object o) throws Exception {
        JAXBContext ctx = JAXBContext.newInstance(c);
        Marshaller marshaller = ctx.createMarshaller();
        StringWriter entityXml = new StringWriter();
        marshaller.marshal(o, entityXml);

        return entityXml.toString();
    }
}

Related

  1. isInternalSunJAXB2Marshaller(@Nullable final Marshaller aMarshaller)
  2. isSunCanonicalization(@Nonnull final Marshaller aMarshaller)
  3. isSunJAXB2Marshaller(@Nullable final Marshaller aMarshaller)
  4. marshal(Class clz, T marshalObj)
  5. marshal(Class c, String xml)
  6. marshal(Class clazz, T obj)
  7. marshal(Class clazz, T object)
  8. marshal(final Object obj, final Class... classes)
  9. marshal(final Object object)