Validating XML against XSD
67,250
Solution 1
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;
}
}
Solution 2
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();
Solution 3
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;
}
}
Solution 4
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:
Author by
Shai
Updated on August 28, 2020Comments
-
Shai over 3 years
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.
-
Andez over 11 yearsThanks for that info. Helped me.
-
mike almost 11 yearsShouldn'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 stackoverflow.com/questions/15732/…
-
HugoPoi over 9 yearsThis code doesn't work when the file to validate contains a DOCTYPE declaration, if someone know why ?
-
Yngvar Kristiansen over 8 yearsIn 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.
-
Elias Vargas about 8 yearsIn 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?