// 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.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;

import org.xml.sax.InputSource;


public class SchemaValidatedParsing
{
    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"); 
        
        SchemaFactory xsf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema xs = xsf.newSchema(new StreamSource(xsd)); 

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

        DocumentBuilder db = dbf.newDocumentBuilder();

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

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