阅读更多
XSD文件 (XML Schema 语言也称作 XML Schema 定义(XML Schema Definition,XSD)。 具体使用方法和定义请参看:
http://www.w3school.com.cn/schema/index.asp
java自jdk1.5以上新增了SchemaFactory类 可以实现对XSD验证的支持,使用起来也很方便。
以下代码可用在JDK1.5+ 验证xml
[java] view plaincopy
public class SimpleErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
System.out.println(e.getMessage());
}
public void error(SAXParseException e) throws SAXException {
System.out.println(e.getMessage());
}
public void fatalError(SAXParseException e) throws SAXException {
System.out.println(e.getMessage());
}
}
SAXParserFactory factory = SAXParserFactory.newInstance();
SchemaFactory schemaFactory =
SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setSchema(schemaFactory.newSchema(
new Source[] {new StreamSource("contacts.xsd")}));
SAXParser parser = factory.newSAXParser();
SAXReader reader = new SAXReader(parser.getXMLReader());
reader.setValidation(false);
reader.setErrorHandler(new SimpleErrorHandler());
reader.read("contacts.xml");
具体的可参看:http://www.edankert.com/validate.html
在JDK1.5之前不提供对XSD的支持,以为在JDK1.5之前众多的XML API已经满天飞 可使用DOM4j + xerces 如果读取XML节点使用XPATH的话 需要saxpath.jar
JDK1.4+DOM4J+xerces 验证xml文件
[c-sharp] view plaincopy
public class ParserErrorHandler implements ErrorHandler {
private static final Logger logger = Logger.getLogger(ParserErrorHandler.class);
public void error(SAXParseException e) throws SAXException {
//logger.error(e);
throw e;
}
public void fatalError(SAXParseException e) throws SAXException {
//logger.error(e);
throw e;
}
public void warning(SAXParseException e) throws SAXException {
//logger.error(e);
throw e;
}
}
--定义SAXReader 后读取xml文件如果不符合XSD规则的话就会跑异常
SAXReader reader = new SAXReader();
reader.setValidation(true);
reader.setFeature("http://xml.org/sax/features/validation", true);
reader.setFeature("http://apache.org/xml/features/validation/schema",
true);
reader
.setProperty(
"http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
“xxx.XSD");
reader.setErrorHandler(new ParserErrorHandler());