title: Generic XML file validator against XML schema (XSD file)
body: <p>I want to create a generic xmlFileValidator with JAXB, that takes a XML file and a schema file, and returns root class's object if the file is valid else throws SAXException or JAXBException.</p>
  
  <pre><code>public class XmlValidateEventHandler implements ValidationEventHandler {
  public static &lt;E&gt; void validator(File xsdFile, File xmlFile, E obj) throws SAXException, JAXBException
  {
      JAXBContext jaxbcontextobj = JaxbUtil.create_context_obj(new ObjectFactory());
      SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      Schema schema = sf.newSchema(xsdFile);
      Unmarshaller unmarshaller = JaxbUtil.create_unmarshl_obj(jaxbcontextobj);
  
      unmarshaller.setSchema(schema);
      unmarshaller.setEventHandler(new XmlValidateEventHandler());        
      javax.xml.bind.JAXBElement&lt;Document&gt;  doc = (javax.xml.bind.JAXBElement&lt;Document&gt;) unmarshaller.unmarshal(xmlFile);
      Document d = doc.getValue();
      obj=(E)d;
  }
  
  @Override
  public boolean handleEvent(ValidationEvent event) {
  
      Logger logger = utility.JaxbUtil.getLogger();
      if(event.getSeverity() == ValidationEvent.ERROR || event.getSeverity() == ValidationEvent.FATAL_ERROR)
      {                           
          //Logger logger = Logger.getLogger(XmlValidateEventHandler.class);              
          logger.error("SEVERITY:  " + event.getSeverity());          
          logger.error("MESSAGE:  " + event.getMessage());            
          logger.error("LINKED EXCEPTION:  " + event.getLinkedException());           
          logger.error("LINE NUMBER:  " + event.getLocator().getLineNumber());
          logger.error("COLUMN NUMBER:  " + event.getLocator().getColumnNumber());
          logger.error("***** Give XML is invalid aginst given XSD *****");
          return false;
      }   
  }
  </code></pre>
  
  <p>}</p>
  
  <p>The following line gives warning ->  </p>
  
  <blockquote>
    <p>Type safety: Unchecked cast from Object to JAXBElement</p>
  </blockquote>
  
  <pre><code>javax.xml.bind.JAXBElement&lt;Document&gt;  doc=(javax.xml.bind.JAXBElement&lt;Document&gt;) unmarshaller.unmarshal(xmlFile);
  </code></pre>
  
  <p>And I am also not able to map the unmarshaled object and set it to <em>E obj</em> which is passed in argument.
  I know it can returned, but i have been asked to set it into that parameter.
  Please help.
  Thanks in advance</p>