How do I validate XML against a DTD (.dtd) - not a schema (.xsd) - using Java 5?
I'm used JAXB to generate some Java classes, which I now use as part
of a web service. Now, I'd like to validate the XML requests that are
coming into my web service. I read this is possible using the
validators and whatnot, but many API's since Java 5 are deprecated,
including most of the 'isValidating()'-related APIs. I also tried to
use the 'ValidationEventCollector' class with the unmarshaller, but it
doesn't actually do anything except take up lines of code.
ValidationEventCollector vec = new ValidationEventCollector();
u.setEventHandler( vec );
Object obj = u.unmarshal( new StreamSource( new StringReader(
xmlStr.toString() ) ) );
if ( vec.hasEvents() ){
ValidationEvent[] validationEvents = vec.getEvents();
System.out.println("There are validation events...");
for (ValidationEvent ve : validationEvents){
int errorLevel = ve.getSeverity();
if ( errorLevel==ValidationEvent.ERROR ||
errorLevel==ValidationEvent.FATAL_ERROR ){
System.out.println("Error or Fatal event..." + ve);
}
else {
System.out.println("Warning event: " + ve);
}
}
Sun has a validation example using a schema (.xsd). I want to use a DTD. The
Sun example is below
(http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/package-summary.html):
// parse an XML document into a DOM tree
DocumentBuilder parser =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("instance.xml"));
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(new File("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an
instance document
Validator validator = schema.newValidator();
// validate the DOM tree
try {
validator.validate(new DOMSource(document));
} catch (SAXException e) {
// instance document is invalid!
}
If you execute this code above and replace 'mySchema.xsd' with a DTD
with the same rules (make it very simple, of course), then you'll
start getting some of the errors I've been getting. On that same Sun
page, there is also a long note about how DTDs are intricately linked
to parsing and how if you try to do one without the other the Sun will
melt and we'll all die. I don't know what it means.
Earn yourself two bucks! That's enough to upgrade to a decent beer
instead of a Budweiser! |