如何在Java中使用XSD验证XML

Java XML验证API可以在Java程序中用于验证XML与XSD是否匹配。在此程序中使用javax.xml.validation.Validator类来验证XML与XSD是否匹配。

验证XML是否符合XSD的规范。

以下是使用的样本XSD和XML文件。Employee.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="https://www.w3.org/2001/XMLSchema" 
targetNamespace="https://www.scdev.com/Employee" 
xmlns:empns="https://www.scdev.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中包含了两个根元素和命名空间,我已经使用Eclipse从XSD创建了两个示例XML文件。EmployeeRequest.xml

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

员工回应.xml

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

這是另一個不符合 Employee.xsd 的 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文件为参数,并在验证成功时返回true,否则返回false。XMLValidation.java

package com.Olivia.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验证API的好处在于我们不需要解析文件,也不需要使用第三方API。

发表回复 0

Your email address will not be published. Required fields are marked *