XmlTools.java 2.0 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;

/**
 * @author mrz
 * @date 20220110
 * XML相关工具类
 */
@Slf4j
public class XmlTools {

    /**
     * 根据XSD校验XML报文是否正确
     * @param xsdPath xsd文件路径
     * @param xmlStr  xml报文内容
     * @return 正确错误
     * @throws IOException 文件读取解析异常
     */
    public static boolean validateXMLSchema(String xsdPath, String xmlStr) throws IOException,SAXException {
        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;
    }

    public static boolean validateXMLSchemaThrowError(String xsdPath, String xmlStr) throws IOException,SAXException {
        ByteArrayInputStream bais = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
        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);

        return true;
    }
}