Java tutorial
//package com.java2s; //License from project: Apache License import java.io.FileInputStream; 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 file path using XSD string and return the resulting JAXB content tree * * @param dummyCtxObject * Dummy contect object for creating related JAXB context * @param strXMLFilePath * XML file path * @param strXSD * XSD * @return resulting JAXB content tree * @throws Exception * in error case */ public static Object doUnmarshallingFromXMLFile(Object dummyCtxObject, String strXMLFilePath, String strXSD) throws Exception { if (dummyCtxObject == null) { throw new RuntimeException("No dummy context object (null)!"); } if (strXMLFilePath == null) { throw new RuntimeException("No XML file path (null)!"); } if (strXSD == null) { throw new RuntimeException("No XSD (null)!"); } Object unmarshalledObject = null; try { JAXBContext jaxbCtx = JAXBContext.newInstance(dummyCtxObject.getClass().getPackage().getName()); Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); // unmarshaller.setValidating(true); /* javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema( new java.io.File(m_strXSDFilePath)); */ StringReader reader = null; FileInputStream fis = null; try { reader = new StringReader(strXSD); javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new StreamSource(reader)); unmarshaller.setSchema(schema); fis = new FileInputStream(strXMLFilePath); unmarshalledObject = unmarshaller.unmarshal(fis); } finally { if (fis != null) { fis.close(); fis = null; } if (reader != null) { reader.close(); reader = null; } } // } catch (JAXBException e) { // //m_logger.error(e); // throw new OrderException(e); } catch (Exception e) { // Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error); throw e; } return unmarshalledObject; } }