首页

定义XMLValidation校验xml工具类实现对指定xml文档进行校验合法有效性代码示例

标签:XMLValidation,xml校验,validation     发布时间:2018-11-20   

一、前言

定义XMLValidation校验XML文档格式工具类,实现对指定字符串路径xsd及其xml文件进行校验、指定URL资源路径xsd及其xml进行校验等,详情参见代码示例。

二、代码示例

import java.io.File;@b@import java.net.URL;@b@import javax.xml.transform.Source;@b@import javax.xml.transform.stream.StreamSource;@b@import javax.xml.validation.Schema;@b@import javax.xml.validation.SchemaFactory;@b@import javax.xml.validation.Validator;@b@@b@public class XMLValidation {@b@	@b@	public static boolean validateXml(String xsdPath, String xmlPath) throws Exception {@b@		SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");@b@		File schemaFile = new File(xsdPath);@b@		Schema schema = schemaFactory.newSchema(schemaFile);@b@		Validator validator = schema.newValidator();@b@		Source source = new StreamSource(xmlPath);@b@		validator.validate(source);@b@		return true;@b@	}@b@@b@	public static boolean validateXml(URL xsdUrl, String xmlPath) throws Exception {@b@		SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");@b@		Schema schema = schemaFactory.newSchema(xsdUrl);@b@		Validator validator = schema.newValidator();@b@		Source source = new StreamSource(xmlPath);@b@		validator.validate(source);@b@		return true;@b@	}@b@@b@	public static boolean validateXml(String xsdPath, File xmlFile)throws Exception {@b@		return validateXml(xsdPath, xmlFile.toURI().toASCIIString());@b@	}@b@@b@	public static boolean validateXml(URL xsdUrl, File xmlFile) throws Exception {@b@		return validateXml(xsdUrl, xmlFile.toURI().toASCIIString());@b@	}@b@	@b@}