编写Java程序使用XSD校验XML文档

本文介绍如何通过编写Java程序来使用XSD(XML Schema Definition)文档来校验XML(EXtensible Markup Language)文档。


现有book.xml和book.xsd,通过编写Java程序来使用book.xsd去校验book.xml。

book.xml:



    
        Java
        Tom
        20
        123456789012345678
    
    
        C
        Jack
        51
        987654321012345678
    

book.xsd:



    
    
        
            
        
    
    
        
            
            
            
            
        
    
    
        
            
        
    

ValidateXmlWithXsd.java:

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;

/**
 * 使用XSD校验XML
 *
 * @author RCNJTECH
 * @date 2017/12/3
 */
public class ValidateXmlWithXsd {

    /**
     * 校验方法
     *
     * @param xmlFilePath XML文件路径
     * @param xsdFilePath XSD文件路径
     */
    public static void validate(String xmlFilePath, String xsdFilePath) {
        try {
            // 创建SchemaFactory实例
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            // 通过向SchemaFactory实例传入XSD文件流创建Schema
            Schema schema = schemaFactory.newSchema(new StreamSource(xsdFilePath));
            // 通过Schema实例构造校验器
            Validator validator = schema.newValidator();
            // 向validate()传入XML文件流
            validator.validate(new StreamSource(xmlFilePath));
            System.out.println("Validate Successfully!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Validate Unsuccessfully!");
        }
    }

    /**
     * main()进行测试
     *
     * @param args null
     */
    public static void main(String[] args) {
        String xmlFilePath = "D:\\IdeaProjects\\XML\\src\\book.xml";
        String xsdFilePath = "D:\\IdeaProjects\\XML\\src\\book.xsd";
        ValidateXmlWithXsd.validate(xmlFilePath, xsdFilePath);
    }
}

运行程序后,毫无疑问地将通过验证,即:

Validate Successfully!

在book.xml文档中,若将标签book的子标签number的值改成负数,即如:


        Java
        Tom
        -20
        123456789012345678

运行后将有如下异常:

Validate Unsuccessfully!
org.xml.sax.SAXParseException; systemId: file:///D:/IdeaProjects/XML/src/book.xml;
    lineNumber: 8; columnNumber: 29; cvc-minInclusive-valid:
    对于类型为 'positiveInteger' 的 minInclusive '1', 值 '-20' 不具有面有效性。
    at com.rcnjtech.service.ValidateXmlWithXsd.validate(ValidateXmlWithXsd.java:32)
    at com.rcnjtech.service.ValidateXmlWithXsd.main(ValidateXmlWithXsd.java:48)

你可能感兴趣的:(编写Java程序使用XSD校验XML文档)