Java使用xsd校验xml

最近项目需要使用xsd对xml进行预校验,于是封装了一个工具类,来完成校验工作。 完整代码如下:

1import java.io.File; 2import java.io.IOException; 3import java.io.StringReader; 4import java.util.ArrayList; 5import java.util.List; 6import java.util.Locale; 7 8import javax.xml.XMLConstants; 9import javax.xml.transform.stream.StreamSource; 10import javax.xml.validation.Schema; 11import javax.xml.validation.SchemaFactory; 12import javax.xml.validation.Validator; 13 14import org.xml.sax.ErrorHandler; 15import org.xml.sax.SAXException; 16import org.xml.sax.SAXParseException; 17 18public class MultiSchemaValidator { 19 20// private static final Logger logger = LoggerFactory.getLogger(MultiSchemaValidator.class); 21 22 static{ 23 System.setProperty("jdk.xml.maxOccurLimit", "9999"); //默认的maxOccur为5000,而我们项目中要求9999 24 Locale.setDefault(Locale.CHINA); //如果项目不考虑国际化的话 25 } 26 27 public static List<SAXParseException> validateXMLSchema(String xsdPath, String xml){ 28 final List<SAXParseException> errors = new ArrayList<>(); 29 try { 30 SchemaFactory factory = 31 SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 32 String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); 33 Schema schema = factory.newSchema(new File(path + xsdPath)); 34 Validator validator = schema.newValidator(); 35 validator.setErrorHandler(new ErrorHandler() { 36 @Override 37 public void warning(SAXParseException exception) throws SAXException { 38// logger.debug("warning ex", exception); 39 } 40 @Override 41 public void fatalError(SAXParseException exception) throws SAXException { 42// logger.debug("fatalError ex", exception); 43 } 44 45 @Override 46 public void error(SAXParseException exception) throws SAXException { 47// logger.debug("error ex", exception); 48 errors.add(exception); 49 } 50 }); 51 validator.validate(new StreamSource(new StringReader(xml))); 52 } catch (IOException | SAXException e) { 53 System.out.println("Exception: "+e.getMessage()); 54 } 55 return errors; 56 } 57 //测试代码 58 public static void main(String[] args) throws Exception { 59 String schemaURI = "xsd/Manifest.xsd"; 60 String xml = ""; 61 62 List<SAXParseException> errors = validateXMLSchema(schemaURI, xml); 63 64 for(SAXParseException ex : errors){ 65 System.out.println(ex.getLineNumber() + "行," + ex.getColumnNumber() + "列," + ex.getMessage()); 66 } 67 } 68}

该代码应该可以完成一般需求。不过需要注意以下问题:

  1. xsd中使用<xs:import> <xs:include> 引入其他xsd文件时,不要将xsd打包到jar中,这种方式不支持jar!的方式访问import文件。
  2. jdk有xml-apis及其实现,但是尝试覆盖其XMLSchemaMessages.properties以便自定义提示语句时出现问题,便引用了 xml-apisxercesImpl,覆盖了org.apache.xerces.impl.msg包下的properties文件。
  3. 上述代码可以完成多schema文件的校验,需保证xsd都在相同路径。若不在同一位置,可参考链接中博客的方式,实现SchemaFactory解析shcema的处理操作。
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )