Listing 3: JDOMValidator.java
import org.jdom.input.SAXBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import org.jdom.*;
import java.io.*;
public class JDOMValidator {
public void validateSchema(String SchemaUrl, String XmlDocumentUrl) {
try { //Create SAXBuilder object
SAXBuilder saxBuilder = new SAXBuilder(
"org.apache.xerces.parsers.SAXParser", true);
//Set SAXBuilder parser to be a validating parser
saxBuilder.setValidation(true);
saxBuilder.setFeature(
"http://apache.org/xml/features/validation/schema", true);
saxBuilder.setFeature(
"http://apache.org/xml/features/validation/schema-full-
checking",true);
saxBuilder.setProperty(
"http://apache.org/xml/properties/schema/external-
noNamespaceSchemaLocation",SchemaUrl);
//Create a ErrorHandler and set ErrorHandler on parser.
Validator handler = new Validator();
saxBuilder.setErrorHandler(handler);
//Parse XML Document
saxBuilder.build(XmlDocumentUrl);
//Output Validation Errors
if (handler.validationError == true)
System.out.println("XML Document has Error:"
+ handler.validationError + " "
+ handler.saxParseException.getMessage());
else
System.out.println("XML Document is valid");
} catch (JDOMException jde) {
}
catch (IOException ioe) {
}
}
//Error Handler class
private class Validator extends DefaultHandler {
public boolean validationError = false;
public SAXParseException saxParseException = null;
public void error(SAXParseException exception) throws SAXException {
validationError = true;
saxParseException = exception;
}
public void fatalError(SAXParseException exception) throws SAXException {
validationError = true;
saxParseException = exception;
}
public void warning(SAXParseException exception) throws SAXException {
}
}
public static void main(String[] argv) {
String SchemaUrl = "catalog.xsd";
String XmlDocumentUrl = "catalog.xml";
JDOMValidator validator = new JDOMValidator();
validator.validateSchema(SchemaUrl, XmlDocumentUrl);
}
}
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|