Here you can find the source of unmarshal(InputStream content, Class
Unmarshal XML data from InputStream by expectedType and return the resulting content tree.
Parameter | Description |
---|---|
content | InputStream with data to unmarshal |
expectedType | appropriate JAXB mapped class |
Parameter | Description |
---|---|
RuntimeException | If any unexpected errors occur while unmarshalling |
public static <T> T unmarshal(InputStream content, Class<T> expectedType)
//package com.java2s; //License from project: Open Source License import com.google.common.collect.Maps; import javax.xml.bind.*; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import java.io.InputStream; import java.util.Map; public class Main { private static final Map<Class<?>, JAXBContext> CONTEXTS = Maps.newHashMap(); /**//from ww w . j a v a 2 s .c o m * <p>Unmarshal XML data from {@code InputStream} by <tt>expectedType</tt> and return the * resulting content tree.</p> * * @param content {@code InputStream} with data to unmarshal * @param expectedType appropriate JAXB mapped class * @return Java content rooted by JAXB Element * @throws RuntimeException If any unexpected errors occur while unmarshalling */ public static <T> T unmarshal(InputStream content, Class<T> expectedType) { return unmarshal(new StreamSource(content), expectedType); } /** * <p>Unmarshal XML data from the specified XML Source by <tt>expectedType</tt> and return the * resulting content tree.</p> * * @param source the XML Source to unmarshal XML data from (providers are only required to support SAXSource, * DOMSource, and StreamSource) * @param expectedType appropriate JAXB mapped class * @return Java content rooted by JAXB Element * @throws RuntimeException If any unexpected errors occur while unmarshalling */ public static <T> T unmarshal(Source source, Class<T> expectedType) { try { Unmarshaller unmarshaller = getContext(expectedType).createUnmarshaller(); return unmarshaller.unmarshal(source, expectedType).getValue(); } catch (JAXBException e) { throw new RuntimeException("Failed to unmarshal object", e); } } private static JAXBContext getContext(Class<?> clazz) { JAXBContext context = CONTEXTS.get(clazz); if (context == null) { try { context = JAXBContext.newInstance(clazz); } catch (JAXBException e) { throw new RuntimeException("Failed to create JAXBContext for type " + clazz, e); } CONTEXTS.put(clazz, context); } return context; } }