Java XML Validate validateXml(final Schema schema, final byte[] xmlBytes)

Here you can find the source of validateXml(final Schema schema, final byte[] xmlBytes)

Description

validate Xml

License

Open Source License

Declaration

public static void validateXml(final Schema schema, final byte[] xmlBytes) throws SAXException 

Method Source Code


//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Schema;

import javax.xml.validation.Validator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {
    public static void validateXml(final Schema schema, final byte[] xmlBytes) throws SAXException {
        validateXml(schema, new ByteArrayInputStream(xmlBytes));
    }// www .j av  a2  s. c o m

    public static void validateXml(final Schema schema, final InputStream inputStream) throws SAXException {
        if (null == schema) {
            throw new IllegalArgumentException(
                    "the schema is required for xml validation. method parameter schema");
        }
        if (null == inputStream) {
            throw new IllegalArgumentException(
                    "the inputStream is required for xml validation. method parameter inputStream");
        }
        try {
            // creating a Validator instance
            final Validator validator = schema.newValidator();

            // preparing the XML file as a SAX source
            final SAXSource source = new SAXSource(new InputSource(inputStream));

            // validating the SAX source against the schema
            validator.validate(source);
        } catch (final IOException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}

Related

  1. validateXml(InputStream xml, InputStream xsd)
  2. validateXML(String schemaPath, String xmlPath)
  3. validateXML(String xml, String schemaURI, DefaultHandler handler)
  4. validateXMLFile(String filename, String schemaFile)