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.
XSD for this XML would look something like this:
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! 🙂