一、前言
定义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@}