Friday, 20 July 2012

XML Schema Validation

Here you will find an example that shows you how to validate one or more XML files according to an XSD Schema file. This project uses JAXP parsing techniques.


Here is the source code:
 
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.xml.sax.SAXException;

public class SchemaValidator {

    public static void main(String args[]) {
        Source xmlFile = null;
        try {
            File schemaFile = new File("C:/file_dir/books.xsd");
            xmlFile = new StreamSource(new File("C:/file_dir/books.xml"));
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(xmlFile);
            System.out.println(xmlFile.getSystemId() + " is valid");
        } catch (SAXException | IOException e) {
            System.out.println(xmlFile.getSystemId() + " is NOT valid");
            System.out.println("Reason: " + e.getLocalizedMessage());
        }
    }
}

Download

Click here to View and Download (File -> Download) the Netbeans Project as well as a demo XML and XSD file.



Configure

Simply extract the XML and XSD files and then open the project and change lines 17 & 18 inside SchemaValidator.java:

File schemaFile = new File("C:/file_dir/books.xsd");
xmlFile = new StreamSource(new File("C:/file_dir/books.xml"));
To match your directory.




Run

Before running the project, if you remove one of the lines from the XML file, i.e:

2000-10-01
Then run it, the SchemaValidator class will report that the XML file is not valid. Using the downloaded XML as is will, by default, result in the SchemaValidator reporting that the XML is valid.

No comments:

Post a Comment