Validating XML using XSD

Reading Time: 2 minutes

Lately, I have been working on a use case where I was asked to parse XML for its validation and retrieve its values.

There are two different document type definitions that can be used with XML:

  • DTD – The original Document Type Definition
  • XML Schema – An XML-based alternative to DTD

A document type definition defines the rules and the legal elements and attributes for an XML document. An XML document validated against a DTD or XSD is both “Well Formed” and “Valid”.

In this blog, I am going to discuss the latter approach. So, let’s just begin with it.

XML Schema

As the name suggests, XML Schema describes the structure of XML just like DTD. To check if your XML file is a “valid” and “well-formed” XML then we need to validate it against its schema file i.e, its XSD.
XSD is XML Schema Definition. Without going into mere theory, let’s dive into its usage.
Consider a sample books.xml file:

XSD for this XML would look something like this:

Validation

Now, let’s do what we intended to do for this blog: Validate this XML file with its XSD.

For that we need an object of SchemaFactory class using the default XML schema provided by W3C , using this object we create an instance of Schema class for our XSD file:

The schema factory constant here is the string http://www.w3.org/2001/XMLSchema which defines XSDs.

After that create a new Validator object.

Now let’s validate this using the validate() method of Validator class.

This method takes the StreamSource of our XML file. The return type of validate() is unit. But this method throws an exception when we try to match our XML file with an incompatible XSD file. Hence let’s wrap this snippet in the try-catch block.

 
The above code reads XML and XSD paths and then validates the XML file with XSD file.

So, that was one of the easiest ways to validate XML file. You can find the complete implementation here.

I hope it was helpful. Happy Coding! 🙂


knoldus-advt-sticker


Written by 

Tech Enthusiast

1 thought on “Validating XML using XSD3 min read

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading