Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.File;

import javax.xml.transform.Source;

import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.SAXException;

public class Main {
    /**
     * Schema factory
     */
    private static final SchemaFactory W3X_XML_SCHEMA_FACTORY = SchemaFactory
            .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);

    /**
     * Validates XML on a XMLschema
     * 
     * @param xmlSchema
     * @param sourceXml
     */
    public static void validateXmlOnSchema(File xmlSchema, Source sourceXml) {
        Schema schema = newSchema(xmlSchema);
        try {
            schema.newValidator().validate(sourceXml);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Could not validate '" + sourceXml.getSystemId() + "' with '" + xmlSchema.getName() + "'!", e);
        }
    }

    /**
     * Validates XML on a XMLschema
     * 
     * @param xmlSchema
     * @param sourceXml
     */
    public static void validateXmlOnSchema(Source xmlSchema, Source sourceXml) {
        Schema schema = newSchema(xmlSchema);
        try {
            schema.newValidator().validate(sourceXml);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Could not validate '" + sourceXml.getSystemId() + "' with '" + xmlSchema.getSystemId() + "'!",
                    e);
        }
    }

    /**
     * Creates a new Schema using the default XML implementation
     * 
     * @param xmlSchema
     * @return Schema
     */
    public static Schema newSchema(File xmlSchema) {
        try {
            return W3X_XML_SCHEMA_FACTORY.newSchema(xmlSchema);
        } catch (SAXException e) {
            throw new RuntimeException("Could not create schema for file '" + xmlSchema.getName() + "'!", e);
        }
    }

    /**
     * Creates a new Schema using the default XML implementation
     * 
     * @param xmlSchema
     * @return Schema
     */
    public static Schema newSchema(Source xmlSchema) {
        try {
            return W3X_XML_SCHEMA_FACTORY.newSchema(xmlSchema);
        } catch (SAXException e) {
            throw new RuntimeException("Could not create schema for file '" + xmlSchema + "'!", e);
        }
    }
}