Thursday, July 30, 2009

Java Source Code to validate XML with XSD

In this article, we are going to learn the source code to validate an XML with an existing XSD.

An XSD (XML schema definition) describes the structure of an XML document. The purpose of an XML Schema is to define the legal building blocks of an XML document

However, without going into much details of XML and XSD, please see the below code to validate an XML with a given XSD.

The XML and XSD which we are using here are SampleXML.xml and SampleXSD.xsd.

import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


public class XMLVaildationWithXSD {

XMLVaildationWithXSD(){

}

public static void main(String[] args) {
XMLVaildationWithXSD xmlValidationWithXSD = new XMLVaildationWithXSD();
xmlValidationWithXSD.validate();
}

private void validate() {
try{
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("./SampleXML.xml"));
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(new File("./SampleXSD.xsd"));
Schema schema = factory.newSchema(schemaFile);
//Schema schema = factory.newSchema(new File("./QoSMCSO.xsd"));
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// validate the DOM tree
try {
//validator.validate(new DOMSource(document));
validator.validate(new StreamSource(new File("./SampleXML.xml")));
System.out.println("XML is valid");
} catch (SAXException e) {
System.out.println("instance document is invalid!"+e.getMessage());
e.printStackTrace();
}catch(Exception exp){
exp.printStackTrace();
}
}catch(ParserConfigurationException pcex){
System.out.println("ParserConfigurationException Message:: "+pcex.getMessage());
pcex.printStackTrace();
}catch(SAXException sexp) {
System.out.println("SAXException Message:: "+sexp.getMessage());
sexp.printStackTrace();
}catch(Exception e){
System.out.println("Message: ");
e.printStackTrace();
}
}

}

No comments:

Total Pageviews