10 October 2010

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

No comments:

Post a Comment