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;
    }
  }
}

No comments:

Post a Comment