// Copyright (c) Keith D Gregory, all rights reserved
package com.kdgregory.example.xml.parsing;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


public class DTDValidatedParsingWithErrorHandler
{
    public static void main(String[] argv) throws Exception
    {
        // this resource is opened here to separate the mechanics of finding it from the process of using it
        // note that the parser is responsible for closing the stream
        InputStream xml = Thread.currentThread().getContextClassLoader().getResourceAsStream("albumsWithEmbeddedDoctype.xml");

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);

        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler()
        {
            @Override
            public void fatalError(SAXParseException exception) throws SAXException
            {
                System.err.println("fatalError: " + exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException
            {
                System.err.println("error: " + exception);
            }

            @Override
            public void warning(SAXParseException exception) throws SAXException
            {
                System.err.println("warning: " + exception);
            }
        });

        Document dom = db.parse(new InputSource(xml));

        System.out.println("root element name = " + dom.getDocumentElement().getNodeName());
    }
}
