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

来源:互联网 发布:mac怎么删除桌面文件 编辑:程序博客网 时间:2024/05/21 22:22

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


如果还不熟悉XML或者XSD,可以到W3Cschool网站进行学习。

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

book.xml:

<?xml version="1.0" encoding="UTF-8"?><booklist xmlns="http://www.rcnjtech.com/book"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://www.rcnjtech.com/book book.xsd">    <book>        <name>Java</name>        <author>Tom</author>        <number>20</number>        <id>123456789012345678</id>    </book>    <book>        <name>C</name>        <author>Jack</author>        <number>51</number>        <id>987654321012345678</id>    </book></booklist>

book.xsd:

<?xml version="1.0" encoding="UTF-8"?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"            targetNamespace="http://www.rcnjtech.com/book"            xmlns="http://www.rcnjtech.com/book"            elementFormDefault="qualified">    <xsd:element name="booklist" type="BOOKLIST"/>    <xsd:complexType name="BOOKLIST">        <xsd:sequence>            <xsd:element name="book" type="BOOK" maxOccurs="unbounded"/>        </xsd:sequence>    </xsd:complexType>    <xsd:complexType name="BOOK">        <xsd:sequence>            <xsd:element name="name" type="xsd:string"/>            <xsd:element name="author" type="xsd:string"/>            <xsd:element name="number" type="xsd:positiveInteger"/>            <xsd:element name="id" type="ID"/>        </xsd:sequence>    </xsd:complexType>    <xsd:simpleType name="ID">        <xsd:restriction base="xsd:string">            <xsd:pattern value="\d{18}"/>        </xsd:restriction>    </xsd:simpleType></xsd:schema>

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的值改成负数,即如:

<book>        <name>Java</name>        <author>Tom</author>        <number>-20</number>        <id>123456789012345678</id></book>

运行后将有如下异常:

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)
原创粉丝点击