Source code: com/sonoma/test/validate.java
1 /*
2 * validate.java
3 */
4 package com.sonoma.test;
5 import javax.xml.parsers.*;
6 import org.xml.sax.*;
7 import org.xml.sax.helpers.*;
8 import java.util.*;
9 import java.io.*;
10 /**
11 * Program to simply load and validate an XML document, requires using a DTD.
12 * Used with examples from xml.apapche.org.
13 */
14 public class validate extends DefaultHandler {
15 static public void main(String[] args) {
16 /*String filename = "./scale.xml";
17 boolean validation = true;
18 // Create a JAXP SAXParserFactory and configure it
19 SAXParserFactory spf = SAXParserFactory.newInstance();
20 spf.setValidating(validation);
21 XMLReader xmlReader = null;
22 try {
23 // Create a JAXP SAXParser
24 SAXParser saxParser = spf.newSAXParser();
25 // Get the encapsulated SAX XMLReader
26 xmlReader = saxParser.getXMLReader();
27 } catch (Exception ex) {
28 System.err.println(ex);
29 System.exit(1);
30 }
31 // Set the ContentHandler of the XMLReader
32 xmlReader.setContentHandler(new validate());
33 // Set an ErrorHandler before parsing
34 xmlReader.setErrorHandler(new MyErrorHandler(System.err));
35 try {
36 // Tell the XMLReader to parse the XML document
37 xmlReader.parse(filename);
38 } catch (SAXException se) {
39 System.err.println(se.getMessage());
40 System.exit(1);
41 } catch (IOException ioe) {
42 System.err.println(ioe);
43 System.exit(1);
44 }
45 System.out.println("Completed Successfully");
46 */
47 }
48
49 // Error handler to report errors and warnings
50 private static class MyErrorHandler implements ErrorHandler {
51 /** Error handler output goes here */
52 private PrintStream out;
53 MyErrorHandler(PrintStream out) {
54 this.out = out;
55 }
56 /**
57 * Returns a string describing parse exception details
58 */
59 private String getParseExceptionInfo(SAXParseException spe) {
60 String systemId = spe.getSystemId();
61 if (systemId == null) {
62 systemId = "null";
63 }
64 String info = "URI=" + systemId +
65 " Line=" + spe.getLineNumber() +
66 ": " + spe.getMessage();
67 return info;
68 }
69 // The following methods are standard SAX ErrorHandler methods.
70 // See SAX documentation for more info.
71 public void warning(SAXParseException spe) throws SAXException {
72 out.println("Warning: " + getParseExceptionInfo(spe));
73 }
74 public void error(SAXParseException spe) throws SAXException {
75 String message = "Error: " + getParseExceptionInfo(spe);
76 throw new SAXException(message);
77 }
78 public void fatalError(SAXParseException spe) throws SAXException {
79 String message = "Fatal Error: " + getParseExceptionInfo(spe);
80 throw new SAXException(message);
81 }
82 }
83 }
84
85