Showing posts with label schema. Show all posts
Showing posts with label schema. Show all posts

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")); 

10 October 2010

DOM editing validation

The example below adds DOM schema validation while modifying the in-memory DOM. It uses DOM load/save example as a basis.
We are adding a text node instead of a comment now, to generate a schema inconsistency.
The checking kicks off when you call normalizeDocument.
Also compare with the parsing validation example.

// SimpleDOML3MemXSD.java

import com.sun.xml.internal.ws.developer.ValidationErrorHandler;
import org.w3c.dom.*;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.*;

import javax.xml.XMLConstants;
import java.io.OutputStreamWriter;

public class SimpleDOML3MemXSD {

  public static void main(String args[]) {
    Document doc;
    try {
      // Create DOM Document using DOM Level 3 Load
      DOMImplementationLS ls = (DOMImplementationLS) DOMImplementationRegistry.
        newInstance().getDOMImplementation("LS");
      LSParser builder = ls.createLSParser(
        DOMImplementationLS.MODE_SYNCHRONOUS,
        "http://www.w3.org/2001/XMLSchema");
      doc = builder.parseURI(args[0]);
      DOMConfiguration config = doc.getDomConfig();
      // for DTD use XMLConstants.XML_DTD_NS_URI
      config.setParameter("schema-type", XMLConstants.W3C_XML_SCHEMA_NS_URI);
      config.setParameter("validate", true);
      config.setParameter("error-handler", new StdErrorHandler());
      //Obtain root elements
      Element root = doc.getDocumentElement();

      // Add text (NOT ALLOWED BY SCHEMA)
      Text text = doc.createTextNode("Training text");
      root.appendChild(text);

      //Now validate
      doc.normalizeDocument();

     // Output to standard output; using DOM Level 3 save
      LSOutput target = ls.createLSOutput();
      target.setCharacterStream(new OutputStreamWriter(System.out));
      ls.createLSSerializer().write(doc, target);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      System.exit(0);
    }
  }

  private static class StdErrorHandler implements DOMErrorHandler {

    public boolean handleError(DOMError e) {
      String prefix = "Severity ";
      if (e.getLocation().getLineNumber() != -1) {
         prefix = "Line " + e.getLocation().getLineNumber()
          + " column  " + e.getLocation().getColumnNumber()
          + ", severity ";
      }
      System.err.println(
        prefix + e.getSeverity()
          + " issue: " + e.getMessage());
      return true;
    }
  }
}

DOM XML Load validation

The example below adds DOM schema validation when you are parsing the XML input file to the DOM load/save example.
The example also features a DOM Level 3 DOMErrorHandler.
Also compare with the editing validation example.

// SimpleDOML3XSD.java

import org.w3c.dom.*;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.*;

import javax.xml.XMLConstants;
import java.io.OutputStreamWriter;

public class SimpleDOML3LSXSD {

  public static void main(String args[]) {
    Document doc;
    try {

      // Create DOM Document using DOM Level 3 Load
      DOMImplementationLS ls = (DOMImplementationLS) DOMImplementationRegistry.
        newInstance().getDOMImplementation("LS");
      LSParser builder = ls.createLSParser(
        DOMImplementationLS.MODE_SYNCHRONOUS,
        // for DTD use XMLConstants.XML_DTD_NS_URI
        XMLConstants.W3C_XML_SCHEMA_NS_URI);
      DOMConfiguration config = builder.getDomConfig();
      config.setParameter("validate", true);
      config.setParameter("error-handler", new StdErrorHandler());
      doc = builder.parseURI(args[0]);

      // Obtain root elements
      Element root = doc.getDocumentElement();

      // Add comment texts
      Comment comment = doc.createComment("Training text");
      root.appendChild(comment);

      // Output to standard output; using DOM Level 3 save
      LSOutput target = ls.createLSOutput();
      target.setCharacterStream(new OutputStreamWriter(System.out));
      ls.createLSSerializer().write(doc, target);

    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      System.exit(0);
    }
  }

  private static class StdErrorHandler implements DOMErrorHandler {

    public boolean handleError(DOMError e) {
      String prefix = "Severity ";
      if (e.getLocation().getLineNumber() != -1) {
         prefix = "Line " + e.getLocation().getLineNumber()
          + " column  " + e.getLocation().getColumnNumber()
          + ", severity ";
      }
      System.err.println(
        prefix + e.getSeverity()
          + " issue: " + e.getMessage());
      return true;
    }
  }
}