zoukankan      html  css  js  c++  java
  • java 校验XSD文件

      因为工程要对接第三方,对方是使用xml格式传输参数,也第一次接触到了xsd文件,在每次调用接口前,都要使用xsd文件校验传输的格式是否符合。

      xsd一般包含多个文件,root,type,code以及子xsd文件,一般先加载root-->code(type)-->子xsd文件,如果全部定义在一个文件,直接加载一个文件就好了。

      以下附上代码:

    package ebshk.adsr.validate;
    
    import org.apache.log4j.Logger;
    
    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.StringReader;
    
    public class ValidateUtil {
    
        private static Logger logger = Logger.getLogger(ValidateUtil.class);
    
        public static Boolean validate(String xml){
            Boolean pass = true;
            try {
                Source root = new StreamSource(ValidateUtil.class.getClassLoader()
                        .getResourceAsStream("xsd/root_elements.xsd"));
    
                Source code = new StreamSource(ValidateUtil.class.getClassLoader()
                        .getResourceAsStream("xsd/code_lists.xsd"));
    
                Source simple = new StreamSource(ValidateUtil.class.getClassLoader()
                        .getResourceAsStream("xsd/simple_types.xsd"));
    
                Source ccd = new StreamSource(ValidateUtil.class.getClassLoader()
                        .getResourceAsStream("xsd/client_centric_data.xsd"));
    
                Source customer = new StreamSource(ValidateUtil.class.getClassLoader()
                        .getResourceAsStream("xsd/customer_account.xsd"));
    
                Source sub = new StreamSource(ValidateUtil.class.getClassLoader()
                        .getResourceAsStream("xsd/sub_account.xsd"));
    
                Source trade = new StreamSource(ValidateUtil.class.getClassLoader()
                        .getResourceAsStream("xsd/trading_account.xsd"));
    
                Source[] sourceArr = {code, simple, ccd, customer, sub, trade, root};
    
                Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(sourceArr);
                Validator validator = schema.newValidator();
                Source s = new StreamSource(new StringReader(xml));
                validator.validate(s);
            }catch (Exception e){
                e.printStackTrace();
                logger.info(e.getMessage());
                pass = false;
            }
            return pass;
        }
    }
  • 相关阅读:
    判断的几种结构
    关于电脑的基础单词笔记
    JAVA插入数据笔记
    完全卸载oracle11g步骤
    hibernate框架
    Java中的字符串比较
    java集合 list与Set、Map区别
    向MyEclipse的项目中导入js文件时,出现小红叉
    Java基础面试题
    java面试题 -- JVM
  • 原文地址:https://www.cnblogs.com/zgz21/p/8854554.html
Copyright © 2011-2022 走看看