Computing Magazine

Validate XML Against XSD in Java

Posted on the 09 June 2014 by Abhishek Somani @somaniabhi
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();
}


}
}


Back to Featured Articles on Logo Paperblog

Magazines