[置顶] Java&Xml教程(九)Java中通过XSD校验XML合法性

Java XML校验API能够通过XSD(XML Schema Definition)校验XML文件内容的合法性。在下面的案例中使用javax.xml.validation.Validator 类通过一个xsd文件来鉴定XML内容合法性。
下面是我们将要用于校验的xsd文件和xml文件的内容。
Employee.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.journaldev.com/Employee" xmlns:empns="http://www.journaldev.com/Employee" elementFormDefault="qualified">

    <element name="empRequest" type="empns:empRequest"></element>

    <element name="empResponse" type="empns:empResponse"></element>

    <complexType name="empRequest">
        <sequence>
            <element name="id" type="int"></element>
        </sequence>
    </complexType>

    <complexType name="empResponse">
        <sequence>
            <element name="id" type="int"></element>
            <element name="role" type="string"></element>
            <element name="fullName" type="string"></element>
        </sequence>
    </complexType>
</schema>

需要注意的是上面的XSD包含两种根元素,同时具有命名空间,下面两种xml文件内容都是合法的:
EmployeeRequest.xml

<?xml version="1.0" encoding="UTF-8"?>
<empns:empRequest xmlns:empns="http://www.journaldev.com/Employee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.journaldev.com/Employee Employee.xsd ">
  <empns:id>5</empns:id>
</empns:empRequest>

EmployeeResponse.xml

<?xml version="1.0" encoding="UTF-8"?>
<empns:empResponse xmlns:empns="http://www.journaldev.com/Employee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.journaldev.com/Employee Employee.xsd ">
  <empns:id>1</empns:id>
  <empns:role>Developer</empns:role>
  <empns:fullName>Pankaj Kumar</empns:fullName>
</empns:empResponse>

下面的一个xml文件内容是不满足XSD约束的:
employee.xml

<?xml version="1.0"?>
<Employee>
    <name>Pankaj</name>
    <age>29</age>
    <role>Java Developer</role>
    <gender>Male</gender>
</Employee>

接下来看如何通过程序来校验这三个xml文件内容是否满足XSD的约束,validateXMLSchema方法接受两个参数,分别是xsd和xml文件的路径,如果xml文件内容是合法的,该方法返回true,否则返回false。
XMLValidation.java

package com.journaldev.xml;

import java.io.File;
import java.io.IOException;

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.SAXException;

public class XMLValidation {

    public static void main(String[] args) {

      System.out.println("EmployeeRequest.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeRequest.xml"));
      System.out.println("EmployeeResponse.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeResponse.xml"));
      System.out.println("employee.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "employee.xml"));

      }

    public static boolean validateXMLSchema(String xsdPath, String xmlPath){

        try {
            SchemaFactory factory = 
                    SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(xsdPath));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new File(xmlPath)));
        } catch (IOException | SAXException e) {
            System.out.println("Exception: "+e.getMessage());
            return false;
        }
        return true;
    }
}

运行上面程序,控制台输出:

EmployeeRequest.xml validates against Employee.xsd? true
EmployeeResponse.xml validates against Employee.xsd? true
Exception: cvc-elt.1: Cannot find the declaration of element 'Employee'.
employee.xml validates against Employee.xsd? false

你可能感兴趣的:([置顶] Java&Xml教程(九)Java中通过XSD校验XML合法性)