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.
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 | // 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