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

import java.io.InputStream;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;

import org.xml.sax.InputSource;


public class SchemaValidationAfterParsing
{
    public static void main(String[] argv) throws Exception
    {
        // these resources are opened here to separate the mechanics of finding them from the process of using them
        // note that the parser is responsible for closing the stream
        InputStream xml = Thread.currentThread().getContextClassLoader().getResourceAsStream("albums.xml"); 
        InputStream xsd = Thread.currentThread().getContextClassLoader().getResourceAsStream("albums.xsd"); 

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

        DocumentBuilder db = dbf.newDocumentBuilder();

        Document dom = db.parse(new InputSource(xml));
        
        SchemaFactory xsf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema xs = xsf.newSchema(new StreamSource(xsd));
        Validator validator = xs.newValidator();
        validator.validate(new DOMSource(dom));

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