Last active
August 29, 2015 14:19
-
-
Save VenkataRaju/c27bbe35877e42c080d3 to your computer and use it in GitHub Desktop.
Validates XML files against XSD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package raju.javautils.xml; | |
import java.io.File; | |
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; | |
import org.xml.sax.SAXParseException; | |
public final class XmlValidator | |
{ | |
private static final String SPACES = " "; | |
public static void main(String[] args) | |
{ | |
if (args.length < 2) | |
{ | |
System.out.println("Usage: java -jar xml-validator-<version>.jar XsdFilePath XmlFilePath1 XmlFilePath2 .."); | |
return; | |
} | |
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); | |
Validator validator; | |
try | |
{ | |
Schema schema = schemaFactory.newSchema(new File(args[0])); | |
validator = schema.newValidator(); | |
} | |
catch (SAXException e) | |
{ | |
System.err.println("XSD file seem to be invalid"); | |
printException(e); | |
return; | |
} | |
for (int i = 1; i < args.length; i++) | |
{ | |
String xmlFilePath = args[i]; | |
try | |
{ | |
validator.validate(new StreamSource(xmlFilePath)); | |
System.out.println("Validation Success. " + xmlFilePath); | |
} | |
catch (Exception e) | |
{ | |
System.err.println("Validation Failed. " + xmlFilePath); | |
printException(e); | |
} | |
} | |
} | |
private static void printException(Exception e) | |
{ | |
if (e instanceof SAXParseException) | |
{ | |
SAXParseException spe = (SAXParseException) e; | |
System.err.println(SPACES + "Line number: " + spe.getLineNumber() + ", Column number: " + spe.getColumnNumber()); | |
System.err.println(SPACES + spe.getMessage()); | |
} | |
else | |
System.err.println(SPACES + e.getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires Java 1.5
Executable Jar file may be found here: https://sites.google.com/site/rajuutils/misc