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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// 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,
      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