Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a xml file against a given xsd file while parsing it with a sax parser?

Tags:

java

xml

xsd

I want to parse a xml file using a SAXParser or XMLReader and verify that the file conforms to a specific xsd file (new File( "example.xsd" )).

It's easy to

  1. do the validation against a xsd file in an extra step using a Validator like in this SO answer.

  2. to validate while parsing by specifying the name of the xsd as "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation" like in this SO answer.

But how can I validate against a new File( "example.xsd" ) while parsing?

like image 481
tangens Avatar asked Oct 27 '09 11:10

tangens


People also ask

How do you validate an XML file using Java with an XSD having an include?

newSchema(schemaFile); // create a Validator instance, which can be used to validate an instance document Validator validator = schema. newValidator(); // validate the DOM tree try { validator. validate(new StreamSource(new File("instance. xml")); } catch (SAXException e) { // instance document is invalid! }

Can we validate XML documents against a 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 do I validate an XML file?

XML documents are validated by the Create method of the XmlReader class. To validate an XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document.


1 Answers

Assuming Java 5 or above, set the schema on the SAXParserFactory:

SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File("myschema.xsd"));
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
saxFactory.setSchema(schema);
SAXParser parser = saxFactory.newSAXParser();
parser.parse("data.xml", new DefaultHandler() {
  // TODO: other handler methods
  @Override
  public void error(SAXParseException e) throws SAXException {
    throw e;
  }
});

You handle validation errors by overriding the error method on your handler and acting as you see fit.

like image 85
McDowell Avatar answered Oct 19 '22 09:10

McDowell