Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.xml.sax.SAXException;
import javax.xml.XMLConstants;

import javax.xml.transform.*;

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import java.io.*;

public class Main {
    public static String validateAgainstXSD(String xml, String xsd) throws IOException {

        InputStream isXml = new ByteArrayInputStream(xml.getBytes());
        InputStream isXsd = new ByteArrayInputStream(xsd.getBytes());

        return isXmlPassingSchemaValidation(isXml, isXsd);
    }

    private static String isXmlPassingSchemaValidation(InputStream xml, InputStream xsd) throws IOException {
        Source xmlSource = new StreamSource(xml);

        try {
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new StreamSource(xsd));
            Validator validator = schema.newValidator();
            validator.validate(xmlSource);
            return null;
        } catch (SAXException e) {
            return e.toString();
        }

    }
}