因为工程要对接第三方,对方是使用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; } }