package com.google.main;
import java.io.File;
import java.io.IOException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class TestXml {
public static void main(String[] args) {
//web中获取 classpath路径
// String classpath= Thread.currentThread().getContextClassLoader().getResource("/").getPath();
// java.net.URLDecoder.decode(xsdPath,"utf-8"); 将路径转码
// realPath=java.net.URLDecoder.decode(realPath,"utf-8"); 将路径解码
//相对路径
String xsdPath = "src/xsd/9906_统计.xsd";
//绝对路径
String filepath = "C:\\xml\\expotXML\\TJ\\201710";
//列出所有文件
getFileNameAndCheck(filepath,xsdPath);
}
//列出所有文件
public static void getFileNameAndCheck(String filepath,String xsdPath) {
File f = new File(filepath);
if (!f.exists()) {
System.out.println(filepath + " 不存在");
return;
}
File fa[] = f.listFiles();
for (int i = 0; i < fa.length; i++) {
File fs = fa[i];
if (fs.isDirectory()) {
System.out.println(fs.getName() + " [是目录]");
} else {
checkXml(xsdPath,fs.getAbsolutePath(),fs.getName());
}
}
}
//校验xml
public static Boolean checkXml(String xsdPath ,String xmlPath,String filename){
Boolean flag= true;
try {
if (validateXml(xsdPath, xmlPath)) {
System.out.println(filename+" 校验通过");
}
} catch (SAXException e) {
flag=false;
System.out.println(filename+" 校验失败");
e.printStackTrace();
} catch (IOException e) {
flag=false;
System.out.println(filename+" 校验失败");
e.printStackTrace();
}
return flag;
}
public static boolean validateXml(String xsdPath, String xmlPath)
throws SAXException, IOException {
// 建立schema工厂
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// 建立验证文档文件对象,利用此文件对象所封装的文件进行schema验证
File schemaFile = new File(xsdPath);
// 利用schema工厂,接收验证文档文件对象生成Schema对象
Schema schema = schemaFactory.newSchema(schemaFile);
// 通过Schema产生针对于此Schema的验证器,利用schenaFile进行验证
Validator validator = schema.newValidator();
// 得到验证的数据源
Source source = new StreamSource(xmlPath);
// 开始验证,成功输出success!!!,失败输出fail
validator.validate(source);
return true;
}
}