Skip to content

Instantly share code, notes, and snippets.

@VenkataRaju
Last active August 29, 2015 14:19
Show Gist options
  • Save VenkataRaju/c27bbe35877e42c080d3 to your computer and use it in GitHub Desktop.
Save VenkataRaju/c27bbe35877e42c080d3 to your computer and use it in GitHub Desktop.
Validates XML files against XSD
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());
}
}
@VenkataRaju
Copy link
Author

d:\MyApps>java -jar xml-validator-0.1.jar
Usage: java -jar xml-validator-<version>.jar XsdFilePath XmlFilePath1 XmlFilePath2 ..

d:\MyApps>java -jar xml-validator-0.1.jar config.xsd valid-config.xml invalid-config.xml
Validation Success. valid-config.xml
Validation Failed.  invalid-config.xml
    Line number: 6, Column number: 43
    cvc-complex-type.3.2.2: Attribute 'search-type' is not allowed to appear in element 'description'.

Requires Java 1.5

Executable Jar file may be found here: https://sites.google.com/site/rajuutils/misc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment