Java tutorial
//package com.java2s; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import org.xml.sax.InputSource; public class Main { private static Map<Class<?>, JAXBContext> contextCache = new HashMap<>(); /** * Unmarshals an XML ({@link String}) to a bean. * * @param xml {@link String} * @param clazz {@link Class} * @return bean * @throws JAXBException */ public static <T> T unmarshal(String xml, Class<T> clazz) throws JAXBException { return unmarshal(new ByteArrayInputStream(xml.getBytes()), clazz); } /** * Unmarshals an XML ({@link File}) to a bean. * * @param file {@link File} * @param clazz {@link Class} * @return bean * @throws JAXBException * @throws IOException */ public static <T> T unmarshal(File file, Class<T> clazz) throws JAXBException, IOException { return unmarshal(new StreamSource(file), clazz); } /** * Unmarshals an XML ({@link InputSource}) to a bean. * * @param is {@link InputSource} * @param clazz {@link Class} * @return bean * @throws JAXBException */ public static <T> T unmarshal(InputSource is, Class<T> clazz) throws JAXBException { return unmarshal(is.getByteStream(), clazz); } /** * Unmarshals an XML ({@link InputStream}) to a bean. * * @param is {@link InputStream} * @param clazz {@link Class} * @return bean * @throws JAXBException */ public static <T> T unmarshal(InputStream is, Class<T> clazz) throws JAXBException { return unmarshal(new StreamSource(is), clazz); } /** * Unmarshals an XML ({@link Source}) to a bean. * * @param source {@link Source} * @param clazz {@link Class} * @return bean * @throws JAXBException */ public static <T> T unmarshal(Source source, Class<T> clazz) throws JAXBException { return createUnmarshaller(clazz).unmarshal(source, clazz).getValue(); } /** * Creates an {@link Unmarshaller} for the given {@link Class}. * * @param clazz {@link Class} * @return {@link Unmarshaller} * @throws JAXBException */ private static <T> Unmarshaller createUnmarshaller(Class<T> clazz) throws JAXBException { return getContext(clazz).createUnmarshaller(); } /** * Returns the corresponding {@link JAXBContext} for the given {@link Class}. * * @param clazz {@link Class} * @return {@link JAXBContext} * @throws JAXBException */ private static <T> JAXBContext getContext(Class<T> clazz) throws JAXBException { synchronized (contextCache) { if (!contextCache.containsKey(clazz)) { contextCache.put(clazz, JAXBContext.newInstance(clazz)); } } return contextCache.get(clazz); } }