XML validation with XSD(XML Schema Definition)


We use XML for storing/keeping some data. In most scenario it becomes very necessary  to check if the XML file is having valid data or not.We can validate a XML file by using a XSD file.XSD file is a kind of document which formally describes the structure of data in the XML file.

Below are the common simple scenario in which XML validation with XSD is useful.

1. If a Web Service(any API) is been created on system which consume/gets a XML request and respond back a success/failure(simple response data) after processing the request.We have to define the contract for incoming XML request  so that client send a valid XML(and so valid data) to the called web service and so that it be processed successfully. XSD will be agreement document between client and server.With this client can validate XML request with this XSD before sending it to Web Service and Web Service can validate the incoming XML request with XSD before processing further the request.

2. Similarly , same thing can be done for response as well, Say if  a web service generate lot of data in the response, we can send them in the form of XML.Now this XML content can also be validated before sending it to the client to make sure client is getting accurate data.In this case also, we can use a XSD file/document which will act as an contract for the response (between server client).

3. Third case can be to cover both of above two scenario.We will use one XSD document/file for incoming XML request  and second XSD document/file for validating response before sending it back to client.This will make sure data validity for both request and response.

 

Below is code which will verify a XML file with a XSD file by using a Java program:

 

XSD file is:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://xyz.com/abc" xmlns:abc="http://xyz.com/abc"
elementFormDefault="qualified">
<xs:element name="Transaction">
<xs:complexType>
<xs:sequence>
<xs:element name="AMCode" minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="10" />
</xs:restriction>
</xs:simpleType>
</xs:element>

<xs:element name="TransactionType" minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="0" />
<xs:maxLength value="3" />
</xs:restriction>
</xs:simpleType>
</xs:element>

<xs:element name="TransactionDate" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:dateTime">
</xs:restriction>
</xs:simpleType>
</xs:element>

</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

XML file which needs to get validate with the above XSD file is :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Transaction xmlns="http://xyz.com/abc">
<AMCode>DCM</AMCode>
<TransactionType>GT2</TransactionType>
<TransactionDate>2013-09-18T13:31:34.681+05:30</TransactionDate>
</Transaction>

Java program which validate the above XML file with that of XSD file is :

package com.xyz.abc.validation;

import java.io.File;
import java.io.IOException;

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

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

public class XMLValidationMain {
private final Logger logger = Logger.getLogger(XMLValidationMain.class);
private static final String INPUT_TRANSACTION_XML_FILE_NAME = "example.xml";
private final static String INPUT_TRANSACTION__XSD_FILE_NAME = "example.xsd";

public static void main(String args[]) {
XMLValidationMain xmlValidationMain= new XMLValidationMain();
try {
xmlValidationMain.isXMLValid(INPUT_TRANSACTION_XML_FILE_NAME, INPUT_TRANSACTION__XSD_FILE_NAME);
} catch (IOException e) {
e.printStackTrace();
}
}

public boolean isXMLValid(String xmlFile, String xsdFile)
throws IOException {

Source xmlFileData = null;
try {
xmlFileData = new StreamSource(xmlFile);
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
File inputXsdFile = new File(xsdFile);
Schema schema = schemaFactory.newSchema(inputXsdFile);
Validator validator = schema.newValidator();
validator.validate(xmlFileData);

if (logger.isInfoEnabled()) {
logger.info(xmlFileData.getSystemId() + " is valid");

}
} catch (IOException e) {
logger.error("Reason: " + e.getMessage());
return false;
} catch (SAXException e) {
logger.error(xmlFileData.getSystemId() + " is NOT valid");
logger.error("Reason: " + e.getMessage());
return false;
}
return true;
}

}

Now since the above XML file is having valid data w.r.t XSD .So output of the above program will be :


INFO  com.xyz.abc.validation.XMLValidationMain  - example.xml is valid

Now , lets us change xml file to make invalid data(Set the value of <AMCode></AMCode> empty and this can not be empty as per XSD ) in it w.r.t XSD.Changed XMl file is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Transaction xmlns="http://xyz.com/abc">
<AMCode></AMCode>
<TransactionType>GT2</TransactionType>
<TransactionDate>2013-09-18T13:31:34.681+05:30</TransactionDate>
</Transaction>

So output of the java program(after changing above xml data) will be :

ERROR com.xyz.abc.validation.XMLValidationMain&amp;amp;nbsp; - example.xml is NOT valid
ERROR com.xyz.abc.validation.XMLValidationMain&amp;amp;nbsp; - Reason: cvc-minLength-valid:
Value '' with length = '0' is not facet-valid with respect to minLength '1' for type '#AnonType_AMCodeTransaction'.

That is it, So we have seen how we can validate a XML with the XSD.Let me know if you have any question about this.

 

2 thoughts on “XML validation with XSD(XML Schema Definition)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s