How can I validate an XML file against a DTD that is stored locally as a file? The XML file does not have any DOCTYPE declaration (or may have one that should then be overridden). I had a look at this thread but besides the fact they are using .NET I doubt that this is a good solution.
Any input appreciated!
In an ideal world, you’d be able to validate using a Validator. Something like this:
Unfortunately, the Sun implementation (at least, as of Java 6) does not include support for creating a Schema instance from a DTD. You might be able to track down a 3rd party implementation.
Your best bet may be to alter the document to include the DTD before parsing using some other mechanism.
You can use a transformer to insert a DTD declaration:
…but this does not seem to replace an existing DTD declaration.
This StAX event reader can do the job:
It will send a given DTD declaration right after the document start and discard any from the old document.
Demo usage:
Note that the XMLEventReader could form the source for some other transformation mechanism that performed validation.
It would be much easier to validate using a W3 schema if you have that option.