Java tutorial
//package com.java2s; //License from project: Apache License import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; public class Main { /** * Unmarshal XML data from XML string using XSD string and return the resulting JAXB content tree * * @param dummyCtxObject * Dummy contect object for creating related JAXB context * @param strXML * XML * @param strXSD * XSD * @return resulting JAXB content tree * @throws Exception * in error case */ public static Object doUnmarshalling(Object dummyCtxObject, String strXML, String strXSD) throws Exception { if (dummyCtxObject == null) { throw new RuntimeException("No dummy context objekt (null)!"); } if (strXML == null) { throw new RuntimeException("No XML document (null)!"); } if (strXSD == null) { throw new RuntimeException("No XSD document (null)!"); } Object unmarshalledObject = null; StringReader readerXSD = null; StringReader readerXML = null; try { JAXBContext jaxbCtx = JAXBContext.newInstance(dummyCtxObject.getClass().getPackage().getName()); Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); readerXSD = new StringReader(strXSD); readerXML = new StringReader(strXML); javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new StreamSource(readerXSD)); unmarshaller.setSchema(schema); unmarshalledObject = unmarshaller.unmarshal(new StreamSource(readerXML)); } catch (Exception e) { // Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error); throw e; } finally { if (readerXSD != null) { readerXSD.close(); readerXSD = null; } if (readerXML != null) { readerXML.close(); readerXML = null; } } return unmarshalledObject; } }