Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;

public class Main {
    private static final String SCHEMALANG = "http://www.w3.org/2001/XMLSchema";

    public static boolean xmlStringValidate(String xmlStr, String xsdPath) {
        boolean flag = false;
        try {
            SchemaFactory factory = SchemaFactory.newInstance(SCHEMALANG);
            File schemaLocation = new File(xsdPath);
            Schema schema = factory.newSchema(schemaLocation);
            Validator validator = schema.newValidator();
            InputStream is = new ByteArrayInputStream(xmlStr.getBytes());
            Source source = new StreamSource(is);
            try {
                validator.validate(source);
                flag = true;
            } catch (SAXException ex) {
                System.out.println(ex.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}