package com.pg.commerce.utils;
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.apache.log4j.Logger;
import org.xml.sax.SAXException;
public class ValidateXML {
public static boolean Validatexml(String xsdpath, String xmlpath)
throws SAXException, IOException {
Logger log = LoggerHelp.getInstance("BazaarVoice");
// 建立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
try {
validator.validate(source);
} catch (Exception ex) {
if(log.isDebugEnabled()){
log.error("Validatexml| >>>error>>>"+ex.toString());
}
ex.printStackTrace();
return false;
}
return true;
}
public static void main(String args[])throws Exception{
System.out.println(Validatexml("D:/CCommerce/IBM/WCDE_ENT70/workspace/config/src/conf/BVvalidateSchema.xsd","C:/Users/sunc002/Desktop/aaa.xml"));
}
}
如果不需要代码实现验证xml的有效性,可以下载xml notepad 2007, view->schemas里面导入你要用于验证的xsd文件,打开xml文件,就会自动验证,如果有错误Error List里面就会显示出来,非常方便。
注意要验证的xml文件必须先用记事本保存成unicode的格式的文件。