43

I need to validate an XML file with a given XSD file. I simply need the method to return true if the validation went fine or false otherwise.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Shai
  • 1,093
  • 4
  • 13
  • 20

4 Answers4

74

Returns simply true or false (also you don't need any external library):

static boolean validateAgainstXSD(InputStream xml, InputStream xsd)
{
    try
    {
        SchemaFactory factory = 
            SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));
        return true;
    }
    catch(Exception ex)
    {
        return false;
    }
}
Micah Hainline
  • 14,367
  • 9
  • 52
  • 85
Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
  • 7
    Shouldn't execptions **just** be used for execptional situations and **not** for control flow? I wouldn't consider it execptional, if execute a 'test'. It can pass, or fail. Two options one has to consider. Also take a look at http://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file – mike Jul 19 '13 at 14:51
  • This code doesn't work when the file to validate contains a DOCTYPE declaration, if someone know why ? – HugoPoi Dec 03 '14 at 16:03
  • 1
    In case someone gets error "No SchemaFactory tha implements [...]", it's maybe because you did the same error as me, which was using the constant XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI. Replace it with the constant mentioned above. – Yngvar Kristiansen Nov 18 '15 at 10:49
  • In the line Schema schema = factory.newSchema(new StreamSource(xsd)); when sending the xsd to validate, it very slow to load the xsd schema, anyone know why this happens? – Elias Vargas Apr 11 '16 at 15:25
5

XMLUnit has some nice classes to do this, there is an example in their README file:

Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSources(Input.fromFile("local.xsd").build());
ValidationResult result = v.validateInstance(new StreamSource(new File("local.xml")));
return result.isValid();
devstopfix
  • 6,698
  • 4
  • 34
  • 32
4
public boolean validate() {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  factory.setValidating(true);

  factory.setAttribute(
        "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
        "http://www.w3.org/2001/XMLSchema");
  factory.setAttribute(
        "http://java.sun.com/xml/jaxp/properties/schemaSource",
        "http://domain.com/mynamespace/mySchema.xsd");
  Document doc = null;
  try {
    DocumentBuilder parser = factory.newDocumentBuilder();
    doc = parser.parse("data.xml");
    return true;
  } catch (Exception e) {
    return false;
  }
}
alexblum
  • 2,198
  • 16
  • 13
3

This might depends on the library you use but googling around with "how to validate xml file in java" gave me these results where you might find your answer:

first interesting result

second interesting result

morandg
  • 1,066
  • 3
  • 14
  • 30