xsd文件校驗xml內容

Notepad++方式:

如何安裝Notepad++插件:http://jingyan.baidu.com/article/4b07be3c69172648b380f383.html


java代碼:

import java.io.File;

import java.util.Iterator;
import java.util.Map;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXValidator;
import org.dom4j.util.XMLErrorHandler;


public class ValidataXML {
public static final String ELEMENT_ALL_LIMITED = "cos-all-limited.2";
public static final String ELEMENT_LOSE = "cvc-complex-type.2.4.a";
public static final String ELEMENT_PATTERN_VALID = "cvc-pattern-valid";
public static final String ELEMENT_REQUIRED_TEXT_LENGTH = "cvc-length-valid";
public static final String ELEMENT_REQUIRED_TEXT_MIN_LENGTH = "cvc-minLength-valid";
public static final String ELEMENT_REQUIRED_TEXT_MAX_LENGTH = "cvc-maxLength-valid";
public static final String ELEMENT_TEXT_VALID = "cvc-type.3.1.3";
public static final String ELEMENT_ENUMERATION = "cvc-enumeration-valid";
public static final String ELEMENT_CHILDREN_LOSE = "cvc-complex-type.2.4.b";
public static final String ELEMENT_REQUIERD_ATTRIBUTE_VALUE_LOSE = "cvc-pattern-valid";
public static final String ELEMENT_OPTIONAL_ATTRIBUTE_VALUE_LOSE = "cvc-attribute.3";
public static final String SINGLE_QUOTE = "'";
public static final String ELEMENT_OPPTIONAL_TEXT_DATATYPE = "cvc-datatype-valid.1.2.1";
public static final String ELEMENT_WITH_ATTRIBUTE_LENGTH = "cvc-complex-type.2.2";
public static final String ELEMENT_ATTRIBUTE_UNIT = "cvc-complex-type.3.1";
public static final String ELEMENT_REQUIRED_ATTRIBUTE_LOSE = "cvc-complex-type.4";


public static String validateXMLByXSD(String xmlScehamDirectory,
String xmlScehmaName, File file) {
String xsdFileName = xmlScehamDirectory + "/" + xmlScehmaName + ".xsd";
try {
XMLErrorHandler errorHandler = new XMLErrorHandler();


SAXParserFactory factory = SAXParserFactory.newInstance();


factory.setValidating(true);


factory.setNamespaceAware(true);


SAXParser parser = factory.newSAXParser();


SAXReader xmlReader = new SAXReader();


Document xmlDocument = xmlReader.read(file);


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 validator = new SAXValidator(parser.getXMLReader());


validator.setErrorHandler(errorHandler);


validator.validate(xmlDocument);


if (errorHandler.getErrors().hasContent()) {
return "0|" + parseSchemaErrors(errorHandler);
}
return "1";
} catch (Exception ex) {
return "0|" + ex.getMessage();
}
}


public static Map<Boolean, String> validateXMLByXSDExt(
String xmlScehamDirectory, String xmlScehmaName, File file) {
Map<Boolean, String> result = new java.util.HashMap();
String xsdFileName = xmlScehamDirectory + "/" + xmlScehmaName + ".xsd";
try {
XMLErrorHandler errorHandler = new XMLErrorHandler();


SAXParserFactory factory = SAXParserFactory.newInstance();


factory.setValidating(true);


factory.setNamespaceAware(true);


SAXParser parser = factory.newSAXParser();


SAXReader xmlReader = new SAXReader();


Document xmlDocument = xmlReader.read(file);


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 validator = new SAXValidator(parser.getXMLReader());


validator.setErrorHandler(errorHandler);


validator.validate(xmlDocument);


if (errorHandler.getErrors().hasContent()) {
result.put(Boolean.valueOf(false),
parseSchemaErrors(errorHandler));
} else {
result.put(Boolean.valueOf(true), "");
}
} catch (Exception ex) {
result.put(Boolean.valueOf(false), ex.getMessage());
return result;
}
return result;
}


public static String parseSchemaErrors(XMLErrorHandler errorHandler) {
StringBuffer errors = new StringBuffer();
boolean trag = false;
Document errorDoc = null;
try {
errorDoc = org.dom4j.DocumentHelper.parseText(errorHandler
.getErrors().asXML());
} catch (org.dom4j.DocumentException e) {
e.printStackTrace();
}
Element root = errorDoc.getRootElement();
for (Iterator<Element> iter = root.elementIterator("error"); iter
.hasNext();) {
if (!trag) {
trag = true;
} else {
errors.append("|");
}
Element childElement = (Element) iter.next();
String childMessage = childElement.getText();
System.err.println(childMessage);
if (childMessage.contains("cos-all-limited.2")) {
errors.append(validateAll(childMessage));
} else if (childMessage.contains("cvc-pattern-valid")) {
String nextErrorMsg = ((Element) iter.next()).getText();
errors.append(validatePatternMsg(childMessage, nextErrorMsg));
} else if (childMessage.contains("cvc-length-valid")) {
String nextErrorMsg = ((Element) iter.next()).getText();
errors.append(validateLengthValid(childMessage, nextErrorMsg));
} else if (childMessage.contains("cvc-minLength-valid")) {
String nextErrorMsg = ((Element) iter.next()).getText();
errors.append(validateMinLengthValid(childMessage, nextErrorMsg));
} else if (childMessage.contains("cvc-maxLength-valid")) {
String nextErrorMsg = ((Element) iter.next()).getText();
errors.append(validateMaxLengthValid(childMessage, nextErrorMsg));
} else if (childMessage.contains("cvc-enumeration-valid")) {
String nextErrorMsg = ((Element) iter.next()).getText();
errors.append(validateEnumeration(childMessage, nextErrorMsg));
} else if (childMessage.contains("cvc-datatype-valid.1.2.1")) {
String nextErrorMsg = ((Element) iter.next()).getText();
errors.append(validateDataType(childMessage, nextErrorMsg));
} else if (childMessage.contains("cvc-complex-type.2.4.b")) {
errors.append(validateChildrenLose(childMessage));
} else if (childMessage.contains("cvc-complex-type.4")) {
errors.append(validateRequiredAttributeLose(childMessage));
} else if (childMessage.contains("cvc-complex-type.2.4.a")) {
errors.append(validateElementLose(childMessage));
} else {
errors.append(childMessage);
}
}
return errors.toString();
}


public static String validateAll(String errorMsg) {
try {
int i = errorMsg.lastIndexOf("element");
int j = errorMsg.lastIndexOf("is invalid");
String realMessage = errorMsg.substring(i + 9, j - 2);
return "Schema中元素" + realMessage + "選擇器 all 最大/小次數設置錯誤";
} catch (Exception e) {
}
return errorMsg;
}


public static String validatePatternMsg(String errorMsg, String nextErrorMsg) {
try {
return


getPrefixMsg(nextErrorMsg)
+ " 賦值非法,原因:正則校驗不通過.正則表達式爲:"
+ errorMsg.substring(errorMsg.lastIndexOf("pattern") + 9,
errorMsg.lastIndexOf("' for type"))
+ " ,當前值:"
+ errorMsg.substring(errorMsg.lastIndexOf("Value '") + 7,
errorMsg.lastIndexOf("' is not facet-valid"));
} catch (Exception e) {
}
return errorMsg;
}


public static String validateLengthValid(String errorMsg,
String nextErrorMsg) {
try {
return


getPrefixMsg(nextErrorMsg)
+ " 長度不正確,原因:要求固定長度爲:"
+ errorMsg.substring(
errorMsg.lastIndexOf("respect to length") + 19,
errorMsg.lastIndexOf("' for type"))
+ "位"
+ " ,當前值:"
+ errorMsg.substring(errorMsg.lastIndexOf("Value '") + 7,
errorMsg.lastIndexOf("' with length"));
} catch (Exception e) {
}
return errorMsg;
}


public static String validateMinLengthValid(String errorMsg,
String nextErrorMsg) {
try {
return


getPrefixMsg(nextErrorMsg)
+ " 長度不正確,原因:要求最小長度爲:"
+ errorMsg
.substring(
errorMsg.lastIndexOf("respect to minLength '") + 22,
errorMsg.lastIndexOf("' for type"))
+ "位"
+ " ,當前值:"
+ errorMsg.substring(errorMsg.lastIndexOf("Value '") + 7,
errorMsg.lastIndexOf("' with length"));
} catch (Exception e) {
}
return errorMsg;
}


public static String validateMaxLengthValid(String errorMsg,
String nextErrorMsg) {
try {
return


getPrefixMsg(nextErrorMsg)
+ " 長度不正確,原因:要求最大長度爲:"
+ errorMsg
.substring(
errorMsg.lastIndexOf("respect to maxLength '") + 22,
errorMsg.lastIndexOf("' for type"))
+ "位"
+ " ,當前值:"
+ errorMsg.substring(errorMsg.lastIndexOf("Value '") + 7,
errorMsg.lastIndexOf("' with length"));
} catch (Exception e) {
}
return errorMsg;
}


public static String validateEnumeration(String errorMsg,
String nextErrorMsg) {
try {
int i = errorMsg.indexOf("[");
int j = errorMsg.indexOf("]");


return getPrefixMsg(nextErrorMsg) + "賦值非法,原因:不在枚舉範圍內";
} catch (Exception e) {
}
return errorMsg;
}


public static String validateDataType(String errorMsg, String nextErrorMsg) {
try {
int m = errorMsg.lastIndexOf("for");
int n = errorMsg.lastIndexOf("'");
String typeName = errorMsg.substring(m + 5, n);
return getPrefixMsg(nextErrorMsg) + "賦值無效,原因:要求類型爲:" + typeName;
} catch (Exception e) {
}
return errorMsg;
}


public static String validateChildrenLose(String errorMsg) {
try {
int m = errorMsg.lastIndexOf("element");
int n = errorMsg.lastIndexOf("' is not complete");
String element = errorMsg.substring(m + 9, n);


int i = errorMsg.lastIndexOf("{");
int j = errorMsg.lastIndexOf("'");
String realMessage = errorMsg.substring(i + 1, j - 1);
return "元素" + element + "不完整,缺少子元素" + realMessage;
} catch (Exception e) {
}
return errorMsg;
}


public static String validateRequiredAttributeLose(String errorMsg) {
try {
int i = errorMsg.indexOf("'");
int j = errorMsg.indexOf("must");
String attributeMessage = errorMsg.substring(i + 1, j - 2);


int m = errorMsg.indexOf("element");
int n = errorMsg.lastIndexOf("'");
String elementMessage = errorMsg.substring(m + 9, n);
return "元素" + elementMessage + "屬性" + attributeMessage + "缺失";
} catch (Exception e) {
}
return errorMsg;
}


public static String validateElementLose(String errorMsg) {
try {
int i = errorMsg.lastIndexOf("element");
int j = errorMsg.lastIndexOf("One of ");
return "元素" + errorMsg.substring(i + 9, j - 3) + "異常,冗餘或重複";
} catch (Exception e) {
e.printStackTrace();
}
return errorMsg;
}


public static String getPrefixMsg(String nextErrorMsg) throws Exception {
String msg = "元素 ";
if (nextErrorMsg.contains("cvc-type.3.1.3")) {
msg = msg + validateElementTextLength(nextErrorMsg);
} else if (nextErrorMsg.contains("cvc-attribute.3")) {
String[] attrMgs = validateElementAttributeUnit(nextErrorMsg);
msg = msg + attrMgs[1] + "屬性 " + attrMgs[0];
}
return msg;
}


public static String validateElementTextLength(String message)
throws Exception {
int i = message.lastIndexOf("element");
int j = message.lastIndexOf("'");
String realMessage = message.substring(i + 9, j);
return realMessage;
}


public static String[] validateElementAttributeUnit(String message)
throws Exception {
int i = message.lastIndexOf("attribute");
int j = message.indexOf("element");
String attributeName = message.substring(i + 11, j - 5);


int n = message.indexOf("is");
String elementName = message.substring(j + 9, n - 2);


int k = message.lastIndexOf("of");
int l = message.lastIndexOf("'");
String unit = message.substring(k + 4, l);


String[] realMessage = { attributeName, elementName, unit };
return realMessage;
}

public static void main(String[] args) {
File file = new File("E:\\XMLWRITE\\Biz42102220160823005078.xml");
//File file = new File("E:\\zz\\xml\\1000301\\Biz500115151030000031.xml");
System.err.println(ValidataXML.validateXMLByXSD("E:\\zz\\xml\\8000101", "8000101", file));

}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章