Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.StringReader; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class Main { /** * The next code store the jaxb context to be used by all threads. Just * create a new jaxb context if the current context doesn't contain the * given class. */ private static final Map<String, JAXBContext> jaxbContextMap = new HashMap<String, JAXBContext>(); /** * This method makes the conversion XML -> JAVA with JAXB. * * @param xml * The XML to convert. * @param classType * The target class to convert. * @param <E> * Class type that resolves to the given XML's NameSpace. * @return The java object representation of the passed XML. * @throws JAXBException * If some problem occur while making the conversion. */ @SuppressWarnings("unchecked") public static <E> E getObjectByXML(String xml, Class<E> classType) throws JAXBException { E retObj = null; if (xml != null) { Unmarshaller unmarshaller = getJaxbContext(classType).createUnmarshaller(); retObj = (E) unmarshaller.unmarshal(new StringReader(stripNonValidXMLCharacters(xml))); } return retObj; } /** * Get * * @param classType * @return * @throws JAXBException */ @SuppressWarnings("rawtypes") private static synchronized JAXBContext getJaxbContext(Class... classTypes) throws JAXBException { JAXBContext retObj = null; String key = ""; for (Class classType : classTypes) { if (!"".equals(key)) { key += ";"; } key += classType.getName(); } retObj = jaxbContextMap.get(key); if (retObj == null) { retObj = JAXBContext.newInstance(classTypes); jaxbContextMap.put(key, retObj); } return retObj; } /** * Strip non valid XML characters. * * @param in * the string * @return the new string */ public static String stripNonValidXMLCharacters(String in) { StringBuffer out = new StringBuffer(); // Used to hold the output. char current; // Used to reference the current character. if (in == null || ("".equals(in))) return ""; // vacancy test. for (int i = 0; i < in.length(); i++) { current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught // here; it should not happen. if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF))) out.append(current); } return out.toString(); } }