Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating XML against XSD [duplicate]

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.

like image 460
Shai Avatar asked Jul 25 '11 11:07

Shai


People also ask

Can we validate XML documents against so schema?

You can validate your XML documents against XML schemas only; validation against DTDs is not supported. However, although you cannot validate against DTDs, you can insert documents that contain a DOCTYPE or that refer to DTDs.

How does XSD validation work?

XSD is a schema language; you use it to define the possible structure and contents of an XML format. A validating parser can then check whether an XML instance document conforms to an XSD schema or a set of schemas.

What is XSD validator?

The WSRR web user interface validates each definition file when starting, and when new or updated definition files are loaded. This is done according to the definition XML Schema Definition (XSD).


1 Answers

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;     } } 
like image 124
Grzegorz Szpetkowski Avatar answered Sep 16 '22 17:09

Grzegorz Szpetkowski