java xsd校验xml

下面使用xsd校验xml

public class XmlValidator {
	private static String errorMsg;
	public static boolean check(String xmlFile, String xsdFile){
		boolean rs = false;		
		rs = checkXSDFormat(xmlFile, xsdFile);
		return rs;
	}
		
	/**
	 * 校验	
	 */
	private static boolean checkXSDFormat(String xmlFile, String xsdFile) {
		SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
		XSDErrorHandler errorHandler = new XSDErrorHandler();
		Validator validator = null;
		try {
			Schema schema = factory.newSchema(new File(xsdFile));
			validator = schema.newValidator();			
			validator.setErrorHandler(errorHandler);
			
		} catch (SAXParseException e) {			
			errorMsg = e.getMessage();
			return false;
		} catch (SAXException e) {			
			errorMsg = e.getMessage();
			return false;
		}		
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(xmlFile);
			validator.validate(new StreamSource(fis));//new File(this.xmlFile)));
		} catch (SAXException e) {			
			errorMsg = e.getMessage();
			return false;
		} catch (IOException e) {			
			errorMsg = e.getMessage();
			return false;
		} finally {
			if(fis != null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if(errorHandler.getError() != null){
			errorMsg = errorHandler.getError();
			return false;
		}
		return true;
	}
	
	public static String getError() {
		return errorMsg;
	}
}

 测试

public class XmlValidate {
	private static String xmlFile = "xml文件路径";
	private static String xsdFile = "对应的xsd文件路径";
	public static void main(String[] args) {
		System.out.println(XmlValidator.check(xmlFile, xsdFile));
		System.out.println(XmlValidator.getError());
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值