Validating XML files
In the scope of different projects I often have to validate XML files. Here is my solution to verify XML files using a schema.
First of all to validate XML files in Java you need create a SchemaFactory
of the W3C XML schema language and you have to compile the schema (let’s assume it’s located in /path/to/schema.xsd
):
SchemaFactory factory = SchemaFactory.newInstance ("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema (new File ("/path/to/schema.xsd"));
Now you’re able to create a validator from the schema.
Validator validator = schema.newValidator ();
In order to validate a XML file you have to read it (let’s assume it’s located in /path/to/file.xml
):
Source source = new StreamSource (new File ("/path/to/file.xml"));
Last but not least you can validate the file:
try
{
validator.validate (source);
System.out.println ("file is valid");
}
catch (SAXException e)
{
System.out.println ("file is invalid:");
System.out.println (e.getMessage ());
}
Download:
JAVA: XMLValidator.java
(Please take a look at the man-page. Browse bugs and feature requests.)
Leave a comment
There are multiple options to leave a comment:
- send me an email
- submit a comment through the feedback page (anonymously via TOR)
- Fork this repo at GitHub, add your comment to the _data/comments directory and send me a pull request
- Fill the following form and Staticman will automagically create a pull request for you:
1 comment
After panicking and scouring the web for 2 days, this has been the ONLY website that has been able to help me! Thank you so so much!