import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.xml.XMLConstants; 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.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXValidator; import org.dom4j.io.XMLWriter; import org.dom4j.util.XMLErrorHandler; import org.xml.sax.SAXException; import com.ufgov.bank.common.log.*; public class validateXml { private static final SimpleDateFormat sdf2 = new SimpleDateFormat( "yyyyMMddHHmmssSSS"); public boolean validate(String xsdUrl, String xml) throws Exception { Date date = new Date(); LogOperation.writeLog("client","xsd文件路径:"+xsdUrl,sdf2.format(date)); LogOperation.writeLog("client","xsd校验前的xml:"+xml,sdf2.format(date)); // 获取Schema工厂类 // 这里的XMLConstants.W3C_XML_SCHEMA_NS_URI的值就是://http://www.w3.org/2001/XMLSchema SchemaFactory factory = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // 获取XSD文件,以流的方式读取到Source中 // XSD文件的位置相对于类文件位置 Source schemaSource = new StreamSource(new FileInputStream(xsdUrl)); Schema schema = factory.newSchema(schemaSource); // 这里是将一个DOM树对象转换成流对象,以便对DOM树对象验证 // 如果是对XML文件进行验证,用FileInputStream即可 ByteArrayInputStream bais = new ByteArrayInputStream( xml.getBytes("GBK")); // 获取验证器,验证器的XML Schema源就是之前创建的Schema Validator validator = schema.newValidator(); XMLErrorHandler errorHandler = new XMLErrorHandler(); validator.setErrorHandler(errorHandler); Source source = new StreamSource(bais); // 执行验证 try { validator.validate(source); if (errorHandler.getErrors().hasContent()) { List errorlist = errorHandler.getErrors().selectNodes("error"); for (int i = 0; i < errorlist.size(); i++) { String errorMsg = getErrorMsg(xsdUrl, (Element) errorlist.get(i)); if (errorMsg != null) { System.out.println(errorMsg); LogOperation.writeLog("client",errorMsg,sdf2.format(date)); } } return false; } else { return true; } } catch (Exception ex) { ex.printStackTrace(); //throw ex; return false; } finally { bais.close(); } } private static String getErrorMsg(String path, Element errorElement) throws Exception { String errorContent = errorElement.getText(); String attribute = "attribute ‘"; String strAttrib = ""; if (errorContent.toLowerCase().indexOf("‘data‘") >= 0) { strAttrib = "dataAttribute"; } else if (errorContent.toLowerCase().indexOf("‘row‘") >= 0) { strAttrib = "rowAttribute"; } if (errorContent.toLowerCase().indexOf(attribute) >= 0) { String tempContent = errorContent.substring(errorContent .toLowerCase().indexOf(attribute) + attribute.length()); String attributeName = tempContent.substring( 0, tempContent.indexOf("‘")); Document document = TextReader.ReadXmlFile(new File(path)); String errorPath = "xs:attributeGroup[@name=‘" + strAttrib + "‘]/" + "xs:attribute[@name=‘" + attributeName + "‘]/@id"; Node errorNode = document.getRootElement().selectSingleNode( errorPath); return errorNode.getText()+":["+errorContent+"]"; } return null; } }
import
java.io.ByteArrayInputStream;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.IOException;
import
java.io.StringWriter;
import
java.text.SimpleDateFormat;
import
java.util.Date;
import
java.util.List;
import
javax.xml.XMLConstants;
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.dom4j.Document;
import
org.dom4j.Element;
import
org.dom4j.Node;
import
org.dom4j.io.OutputFormat;
import
org.dom4j.io.SAXValidator;
import
org.dom4j.io.XMLWriter;
import
org.dom4j.util.XMLErrorHandler;
import
org.xml.sax.SAXException;
import
com.ufgov.bank.common.log.*;
public
class
validateXml {
private
static
final
SimpleDateFormat sdf2 =
new
SimpleDateFormat(
"yyyyMMddHHmmssSSS"
);
public
boolean
validate(String xsdUrl, String xml)
throws
Exception {
Date date =
new
Date();
LogOperation.writeLog(
"client"
,
"xsd文件路径:"
+xsdUrl,sdf2.format(date));
LogOperation.writeLog(
"client"
,
"xsd校验前的xml:"
+xml,sdf2.format(date));
// 获取Schema工厂类
// 这里的XMLConstants.W3C_XML_SCHEMA_NS_URI的值就是://http://www.w3.org/2001/XMLSchema
SchemaFactory factory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// 获取XSD文件,以流的方式读取到Source中
// XSD文件的位置相对于类文件位置
Source schemaSource =
new
StreamSource(
new
FileInputStream(xsdUrl));
Schema schema = factory.newSchema(schemaSource);
// 这里是将一个DOM树对象转换成流对象,以便对DOM树对象验证
// 如果是对XML文件进行验证,用FileInputStream即可
ByteArrayInputStream bais =
new
ByteArrayInputStream(
xml.getBytes(
"GBK"
));
// 获取验证器,验证器的XML Schema源就是之前创建的Schema
Validator validator = schema.newValidator();
XMLErrorHandler errorHandler =
new
XMLErrorHandler();
validator.setErrorHandler(errorHandler);
Source source =
new
StreamSource(bais);
// 执行验证
try
{
validator.validate(source);
if
(errorHandler.getErrors().hasContent()) {
List errorlist = errorHandler.getErrors().selectNodes(
"error"
);
for
(
int
i =
0
; i < errorlist.size(); i++) {
String errorMsg = getErrorMsg(xsdUrl,
(Element) errorlist.get(i));
if
(errorMsg !=
null
) {
System.out.println(errorMsg);
LogOperation.writeLog(
"client"
,errorMsg,sdf2.format(date));
}
}
return
false
;
}
else
{
return
true
;
}
}
catch
(Exception ex) {
ex.printStackTrace();
//throw ex;
return
false
;
}
finally
{
bais.close();
}
}
private
static
String getErrorMsg(String path, Element errorElement)
throws
Exception {
String errorContent = errorElement.getText();
String attribute =
"attribute ‘"
;
String strAttrib =
""
;
if
(errorContent.toLowerCase().indexOf(
"‘data‘"
) >=
0
) {
strAttrib =
"dataAttribute"
;
}
else
if
(errorContent.toLowerCase().indexOf(
"‘row‘"
) >=
0
) {
strAttrib =
"rowAttribute"
;
}
if
(errorContent.toLowerCase().indexOf(attribute) >=
0
) {
String tempContent = errorContent.substring(errorContent
.toLowerCase().indexOf(attribute) + attribute.length());
String attributeName = tempContent.substring(
0
,
tempContent.indexOf(
"‘"
));
Document document = TextReader.ReadXmlFile(
new
File(path));
String errorPath =
"xs:attributeGroup[@name=‘"
+ strAttrib +
"‘]/"
+
"xs:attribute[@name=‘"
+ attributeName +
"‘]/@id"
;
Node errorNode = document.getRootElement().selectSingleNode(
errorPath);
return
errorNode.getText()+
":["
+errorContent+
"]"
;
}
return
null
;
}
}
原文:http://www.cnblogs.com/ITinfo/p/5109428.html