public class XMLValidator {
/**
* 简单校验
*
* @param xsdFileName
* @param xmlFileName
* @return
*/
private static boolean validateXMLByXSD(String xsdFileName,String xmlFileName, final int maxErrorLineNum) {
final List<String> errorLines = new ArrayList<String>();
boolean flag = true;
try {
//创建默认的XML错误处理器
ErrorHandler errorHandler = new ErrorHandler() {
public void error(SAXParseException e) throws SAXException {
if (errorLines.size() < maxErrorLineNum) {
errorLines.add("Line[" + e.getLineNumber() + "]" + " " + "ERROR: " + e.getMessage());
} else {
throw new SAXException("[ERROR]: too many errors", e);
}
}
public void fatalError(SAXParseException e) throws SAXException {
// System.out.println("[FATAL]: " + e);
throw new SAXException("[FATAL]: Line[" + e.getLineNumber() + "] " + e);
}
public void warning(SAXParseException e) {
// System.out.println("[WARN]: " + e);
}
};
//获取基于 SAX 的解析器的实例
SAXParserFactory factory = SAXParserFactory.newInstance();
//解析器在解析时验证 XML 内容。
factory.setValidating(true);
//指定由此代码生成的解析器将提供对 XML 名称空间的支持。
factory.setNamespaceAware(true);
//使用当前配置的工厂参数创建 SAXParser 的一个新实例。
SAXParser parser = factory.newSAXParser();
//创建一个读取工具
SAXReader xmlReader = new SAXReader();
//获取要校验xml文档实例
Document xmlDocument = (Document) xmlReader.read(new File(xmlFileName));
//设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在 [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。
parser.setProperty(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
parser.setProperty(
"http://java.sun.com/xml/jaxp/properties/schemaSource",
"file:" + xsdFileName);
//创建一个SAXValidator校验工具,并设置校验工具的属性
SAXValidator validator = new SAXValidator(parser.getXMLReader());
//设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
validator.setErrorHandler(errorHandler);
//校验
validator.validate(xmlDocument);
if (errorLines.size() != 0) {
for(String error : errorLines) {
System.out.println(error);
}
System.out.println("XML文件通过XSD文件校验失败!!!");
flag = false;
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
return flag;
}
/**
* 复杂校验
*
* @param validateType
* @param xmlFilePath
* @param xsdFileName
*/
public static boolean validateXML(String validateType,String xmlFileName,String xsdFileName) {
long startTime = System.currentTimeMillis();
if (validateType.equals("isWellformed")) {
boolean isWellformed = isWellformed(xmlFileName);
if (isWellformed) {
System.out.println("XML document is well formed");
System.out.println((System.currentTimeMillis() - startTime) / 1000.0 + " s");
//System.exit(0);
} else {
System.out.println("XML document is not well formed");
System.out.println((System.currentTimeMillis() - startTime) / 1000.0 + " s");
//System.exit(1);
}
return isWellformed;
} else if (validateType.equals("isValidated")) {
// 首先检查xml文件格式是否是正确生成的
boolean isValidated = isWellformed(xmlFileName);
// 根据给定的scheme文件校验
if(isValidated) {
isValidated = validateXMLByXSD(xsdFileName, xmlFileName,50);
}
if (isValidated) {
System.out.println("XML document is valid");
System.out.println((System.currentTimeMillis() - startTime) / 1000.0 + " s");
//System.exit(0);
} else {
System.out.println("XML document is invalid");
System.out.println((System.currentTimeMillis() - startTime) / 1000.0 + " s");
//System.exit(1);
}
return isValidated;
}
return false;
}
static public boolean isWellformed(String xmlFilePath) {
boolean isWellformed = true;
String line = "";
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = null;
saxParser.parse(new File(xmlFilePath), handler);
} catch (IOException e) {
isWellformed = false;
line = "IOException: " + e.getMessage();
} catch (SAXException e) {
isWellformed = false;
line = "SAXException: " + e.getMessage();
} catch (Exception e) {
isWellformed = false;
line = "Exception: " + e.getMessage();
}
if (!isWellformed) {
System.out.println(line);
}
return isWellformed;
}
public static boolean isValidated(String xmlFilePath, String xsdFileName, final int maxErrorLineNum) {
final List<String> errorLines = new ArrayList<String>();
boolean isValid = false;
String[] schemaDirNames = xsdFileName.split(",");
if (schemaDirNames == null || schemaDirNames.length == 0) {
return false;
}
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Source schemas[] = new Source[schemaDirNames.length];
for (int i = 0; i < schemaDirNames.length; i++) {
schemas[i] = new StreamSource(schemaDirNames[i]);
}
try {
Schema schema = factory.newSchema(schemas);
Validator validator = schema.newValidator();
validator.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException e) throws SAXException {
if (errorLines.size() < maxErrorLineNum) {
errorLines.add("Line[" + e.getLineNumber() + "]" + " " + "ERROR: " + e.getMessage());
} else {
throw new SAXException("[ERROR]: too many errors", e);
}
}
public void fatalError(SAXParseException e) throws SAXException {
// System.out.println("[FATAL]: " + e);
throw new SAXException("[FATAL]: Line[" + e.getLineNumber() + "] " + e);
}
public void warning(SAXParseException e) {
// System.out.println("[WARN]: " + e);
}
});
validator.validate(new StreamSource(xmlFilePath));
if (errorLines.size() == 0) {
isValid = true;
}
} catch (SAXException e) {
errorLines.add("SAXException: " + e.getMessage());
} catch (FileNotFoundException e) {
errorLines.add("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
errorLines.add("IOException: " + e.getMessage());
}
if (!isValid) {
for (String line : errorLines) {
System.out.println(line);
}
}
return isValid;
}
}
XSD校验XML JAVA实现
最新推荐文章于 2023-12-10 23:40:23 发布