XML是可扩展标记语言,也就是说其中的标记我们可以按照我们的意愿生成,只要符合语法规则就认为是合法的。
但是很多情况下我们需要根据一定的验证规则对xml文档实施限制。当我们书写一个xml文档的时候,通过验证文档对其进行验证,可以保证所书写的文档是合法合理的。这样我们的程序才可以对其进行适当的操作。不然随意写一个符合语法的xml文档,我们的程序显然不能总是能对其进行操作。
验证文档对所书写的xml文档进行合理合法的验证,验证文档有两种格式,一种为dtd,一种为xsd(schema形式)。
Xsd文档主要起一个验证作用!
我们可以在操作一个传输过来的,或者新生成的xml文档先进行验证,然后再进行解析,这样可以保证操作成功。
在此,我们使用schema格式的文档对xml进行验证。
<?xml version="1.0" encoding="UTF-8"?>
<!--W 3C Schema generated by XMLSpy v2008 (http://www.altova.com)-->
<xs:schema xmlns="http://www.frank.com"
xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.frank.com" elementFormDefault="qualified">
<xs:element name="students">
<xs:complexType>
<xs:sequence>
<xs:element ref="student" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="age"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:byte"/>
</xs:schema>
<?xml version="1.0" encoding="UTF-8"?>
<my:students xmlns:my="http://www.frank.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<my:student>
<my:name>tom</my:name>
<my:age>23</my:age>
</my:student>
<my:student>
<my:name>mike</my:name>
<my:age>23</my:age>
</my:student>
</my:students>
package test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
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.xml.sax.SAXException;
public class TestXML {
/**
* @param args
*/
public static void main(String[] args) throws SAXException, IOException {
// 建立schema工厂
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// 建立验证文档文件对象,利用此文件对象所封装的文件进行schema验证
File schemaFile = new File("C:/Documents and Settings/pengch/workspace/xmlschema/test/students.xsd");
// 利用schema工厂,接收验证文档文件对象生成Schema对象
Schema schema = schemaFactory.newSchema(schemaFile);
// 通过Schema产生针对于此Schema的验证器,利用students.xsd进行验证
Validator validator = schema.newValidator();
// 得到验证的数据源,就是students.xml
Source source = new StreamSource("C:/Documents and Settings/pengch/workspace/xmlschema/test/students.xml");
// 开始验证,成功输出success!!!,失败输出fail
try {
validator.validate(source);
System.out.println("success!!!");
} catch (Exception ex) {
System.out.println("fail");
}
}
}
抽象一下:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DefaultErrorHandler implements ErrorHandler {
protected static Log logger = LogFactory.getLog(DefaultErrorHandler.class);
public void error(SAXParseException exception) throws SAXException {
if(logger.isErrorEnabled()) {
logger.error("XML file is invalid", exception);
}
throw new SAXException(exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
if(logger.isErrorEnabled()) {
logger.error("XML file is invalid", exception);
}
throw new SAXException(exception);
}
public void warning(SAXParseException exception) throws SAXException {
if(logger.isWarnEnabled()) {
logger.warn("Warning", exception);
}
exception.printStackTrace();
}
}
import java.io.IOException;
import java.io.InputStream;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
public class DefaultSchemaValidator extends SchemaValidator {
private InputStream schemaStream;
/**
* 构造函数
* @param schemaStream schema文件输入流
*/
public DefaultSchemaValidator(InputStream schemaStream) {
this.schemaStream = schemaStream;
}
/**
* 构造函数
* @param clz
* @param schemaFile schema文件
*/
public DefaultSchemaValidator(Class clz, String schemaFile) {
this.schemaStream = clz.getResourceAsStream(schemaFile);
}
public DefaultSchemaValidator(ClassLoader classLoader, String schemaFile) {
this.schemaStream = classLoader.getResourceAsStream(schemaFile);
}
public void validate(InputStream xmlStream, ErrorHandler errorHandler) throws SAXException, IOException {
Schema schema = createSchema(schemaStream);
Validator validator = schema.newValidator();
validator.setErrorHandler(errorHandler);
validator.validate(new StreamSource(xmlStream));
}
/**
* 验证给定的xml是否合法
*
* @return
* @throws SAXException
*/
protected Schema createSchema(InputStream schemaStream) throws SAXException {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W 3C _XML_SCHEMA_NS_URI);
return schemaFactory.newSchema(new StreamSource(schemaStream));
}
}
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
public abstract class SchemaValidator {
public abstract void validate(InputStream xmlStream, ErrorHandler errorHandler) throws SAXException, IOException;
public void validate(InputStream xmlStream) throws SAXException, IOException {
validate(xmlStream, new DefaultErrorHandler());
}
}
import java.io.IOException;
import org.xml.sax.SAXException;
import com.DefaultSchemaValidator;
import com.SchemaValidator;
public class TestXML2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SchemaValidator schemaValidator= new DefaultSchemaValidator(TestXML2.class,"Students.xsd");
try {
schemaValidator.validate(TestXML2.class.getResourceAsStream("students.xml"));
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}