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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM