How can I validate XML using java?

I need to parse a bunch of incoming XML documents, but it doesn't contain a DOCTYPE (they all have different DTDs). DTD is created by me. How can I validate an XML file against a DTD that is stored locally as a file? I have the following requirement:

  • All DTDs (for different XML) will be loaded into memory once, when the incoming XML is not viewed in the locally stored scope.
  • validate incoming XML based on the loaded DTD file.



source to share

1 answer

For the SAX parser, you need to use a local entity resolver, here is an example of its implementation:

class LocalEntityResolver implements EntityResolver {

private static final Logger LOG = ESAPI.getLogger(LocalEntityResolver.class);
private static final Map<String, String> DTDS;
static {
    DTDS = new HashMap<String, String>();
    DTDS.put("-//W3C//DTD XHTML 1.0 Transitional//EN",
    DTDS.put("-//W3C//ENTITIES Latin 1 for XHTML//EN",
    DTDS.put("-//W3C//ENTITIES Symbols for XHTML//EN",
    DTDS.put("-//W3C//ENTITIES Special for XHTML//EN",

public InputSource resolveEntity(String publicId, String systemId)
        throws SAXException, IOException {
    InputSource input_source = null;
    if (publicId != null && DTDS.containsKey(publicId)) {
        LOG.debug(Logger.EVENT_SUCCESS, "Looking for local copy of [" + publicId + "]");

        final String dtd_system_id = DTDS.get(publicId);
        final String file_name = dtd_system_id.substring(
                dtd_system_id.lastIndexOf('/') + 1, dtd_system_id.length());

        InputStream input_stream = FileUtil.readStreamFromClasspath(
                file_name, "your/dtd/location",
        if (input_stream != null) {
            LOG.debug(Logger.EVENT_SUCCESS, "Found local file [" + file_name + "]!");
            input_source = new InputSource(input_stream);

    return input_source;




All Articles