Java tutorial
//package com.java2s; //License from project: Apache License import java.io.FileInputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; public class Main { /** * Unmarshal XML data from XML file path using XSD from file path and return the resulting JAXB content tree * * @param dummyCtxObject * Dummy contect object for creating related JAXB context * @param strXMLFilePath * XML file path * @param strXSDFilePath * XSD file path * @return resulting JAXB content tree * @throws Exception * in error case */ public static Object doUnmarshallingFromFiles(Object dummyCtxObject, String strXMLFilePath, String strXSDFilePath) 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 (strXSDFilePath == null) { throw new RuntimeException("No XSD file path (null)!"); } Object unmarshalledObject = null; FileInputStream fis = 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(strXSDFilePath)); unmarshaller.setSchema(schema); // register schema for validation fis = new FileInputStream(strXMLFilePath); unmarshalledObject = unmarshaller.unmarshal(fis); } catch (Exception e) { // Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error); throw e; } finally { if (fis != null) { fis.close(); fis = null; } } return unmarshalledObject; } }