Download Wiley Professional XML Development with Apache Tools: Xerces, Xalan, FOP, Cocoon, Axis, Xindice

Transcript
01 543555 Ch01.qxd
11/5/03
9:40 AM
Page 21
Xerces
Here’s the SAXMain program, enhanced to perform schema validation:
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:
/*
*
* SchemaValidateMain.java
*
* Example from "Professional XML Development with Apache Tools"
*
*/
package com.sauria.apachexml.ch1;
import java.io.IOException;
import
import
import
import
import
import
org.apache.xerces.parsers.SAXParser;
org.xml.sax.EntityResolver;
org.xml.sax.SAXException;
org.xml.sax.SAXNotRecognizedException;
org.xml.sax.SAXNotSupportedException;
org.xml.sax.XMLReader;
public class SchemaValidateMain {
public static void main(String[] args) {
XMLReader r = new SAXParser();
try {
r.setFeature("http://xml.org/sax/features/validation",
true);
r.setFeature(
"http://apache.org/xml/features/validation/schema",
true);
} catch (SAXNotRecognizedException snre) {
snre.printStackTrace();
} catch (SAXNotSupportedException snre) {
snre.printStackTrace();
}
BookHandler bookHandler = new BookHandler();
r.setContentHandler(bookHandler);
r.setErrorHandler(bookHandler);
EntityResolver bookResolver = new BookResolver();
r.setEntityResolver(bookResolver);
try {
r.parse(args[0]);
System.out.println(bookHandler.getBook().toString());
} catch (SAXException se) {
System.out.println("SAX Error during parsing " +
se.getMessage());
se.printStackTrace();
} catch (IOException ioe) {
System.out.println("I/O Error during parsing " +
ioe.getMessage());
ioe.printStackTrace();
} catch (Exception e) {
System.out.println("Error during parsing " +
e.getMessage());
21