1 December 2014

Setting the JAXP validation file (updated)

A JAXP parser validates (version >= 1.2) by default using a DTD. Here are some variations that can be used when validating

  • If you are using SAX and obtained this parser from the SAXParserFactory:
  • javax.xml.parsers.SAXParser parser
    • To validated using a schema (xsd) add this line of code to your parser setup:
    • parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", 
        XMLConstants.W3C_XML_SCHEMA_NS_URI); 
    • To specify the schema file in your code (for both DTD and XSD) add this line to your parser setup:
    • parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", 
        new File("checkers.xsd")); 
                  SL-385.B: add to code 3-2 after line 17   
      • The source can be a File, InputStream, InputSource or an Object array containing these types
  • If you are using DOM, and you created this DocumentBuilderFactory instance :
  • javax.xml.parsers.DocumentBuilderFactory builder
    • To validated using a schema (xsd) add this line of code to your parser setup:
    • builder.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", 
        XMLConstants.W3C_XML_SCHEMA_NS_URI);
      • XMLConstants.W3C_XML_SCHEMA_NS_URI = http://www.w3.org/2001/XMLSchema
      • The corresponding constant for DTD (the default) in these cases is  
      • XMLConstants.XML_DTD_NS_URI = http://www.w3.org/TR/REC-xml
    • To specify the schema file in your code (for both DTD and XSD) add this line to your parser setup:
    • builder.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", 
        new File("checkers.xsd"));