Monday 9 June 2014

Textual Representation of logo

Validate XML against XSD in Java

Here's the sample java program which will validate xml file against a particular schema file .

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;


public class XmlValidator
{
 public static void main(String[] args)
 {
  try {
      

      SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

      Schema sch= schemaFactory .newSchema(new StreamSource("D:\\example.xsd"));
      Validator validator = sch.newValidator();

      validator.validate(new StreamSource("D:\\example.xml"));
      
      System.out.println("Successfully validated");

  } catch (Exception e) {
      e.printStackTrace();
  } 
  
  
 }
}