【Java】【XML】【SAX】XMLスキーマチェック [1]

XMLスキーマチェック

http://java.sun.com/javase/ja/6/docs/ja/api/javax/xml/validation/package-summary.html
が使えそう

サンプル

package xml;

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
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.SAXException;

public class XMLValidator {
    String path = "D:\\test\\";
    public boolean xmlValidation() {
        // parse an XML document into a DOM tree
        DocumentBuilder parser;
        Document document;
        try {
            parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();

            // create a SchemaFactory capable of understanding WXS schemas
            SchemaFactory factory
                = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    
            // load a WXS schema, represented by a Schema instance
            Source schemaFile = new StreamSource(new File(path + "text.xsd"));
            Schema schema = factory.newSchema(schemaFile);
    
            // create a Validator instance, which can be used to validate an instance document
            Validator validator = schema.newValidator();
    
            // validate the DOM tree
            document = parser.parse(new File(path + "test.xml"));
            validator.validate(new DOMSource(document));
        } catch (SAXException ex) {
            System.out.println("From SAXException");
            ex.printStackTrace();
            return false;
        } catch (ParserConfigurationException ex) {
            System.out.println("From ParserConfigurationException");
            ex.printStackTrace();
            return false;
        } catch (IOException ex) {
            System.out.println("From IOException");
            ex.printStackTrace();
            return false;
        } catch (Exception ex) {
            System.out.println("From Exception");
            ex.printStackTrace();
            return false;
        }
        
        return true;
    }
}