上一篇文章"XML Schema检验XML文档结构"中,简单介绍了XML Schema及其写法,这篇主要针对java开发者,在程序中检验XML的有效性。
由于程序中经常会对xml的validation进行检验,通过DOM解析再一项一项check的方式,陈旧而且写起来繁杂。本文介绍一种快速检验xml的方法,借助javax.xml.validation包下的Validator, Schema, SchemaFactory等类,通过传入XML Schema Definition(XSD)文件进行验证。
代码如下:
public static void main(String[] args) throws IOException, SAXException {
String xmlFile = "test.xml"
String xsdFile = "test.xsd"
// 1. Lookup a factory for the W3C XML Schema language
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// 2. Compile the schema.
File schemaLocation = new File(xsdFile);
Schema schema = factory.newSchema(schemaLocation);
// 3. Get a validator from the schema.
Validator validator = schema.newValidator();
// 4. Parse the document you want to check.
Source source = new StreamSource(xmlFile);
// 5. Check the document
try {
validator.validate(source);
System.out.println(xmlFile + " is valid.");
} catch (SAXException ex) {
System.out.println(xmlFile + " is not valid because ");
System.out.println(ex.getMessage());
}
}
Validator的validate方法用于检验其正确性,如果不符合XSD描述,则会SAXException,并附带出错信息。
Hope it can relax your eyes : )