XSDValidateWithXML.java 1.2 KB
package com.tianbo.analysis.tools;

import lombok.extern.slf4j.Slf4j;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
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 java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

@Slf4j
public class XSDValidateWithXML {
    public static boolean validateXMLSchema(String xsdPath, String xmlStr) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
        try {
            SchemaFactory factory =
                    SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(xsdPath));
            Validator validator = schema.newValidator();

            Source source = new StreamSource(bais);
            validator.validate(source);
        } catch (IOException | SAXException e) {
            e.printStackTrace();
            log.error("Exception:{}",e.getMessage());
            return false;
        }finally {
            bais.close();
        }
        return true;
    }
}