如何在Java中针对XSD验证XML

本文介绍如何使用Java XML验证API来验证XML文件是否符合XSD模式。通过示例展示了如何利用javax.xml.validation.Validator类进行验证过程,包括正确和错误的XML文件示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java XML Validation API can be used to validate XML against XSD in java program. javax.xml.validation.Validator class is used in this program to validate xml against xsd in java.

Java XML验证API可用于针对Java程序中的XSD验证XML。 此程序中使用javax.xml.validation.Validator类针对Java中的xsd验证xml。

针对XSD验证XML (Validate XML against XSD)

Validate XML against XSD java, java xml validation, xsd validator java

Here are the sample XSD and XML files used.


这是使用的示例XSD和XML文件。

Employee.xsd

Employee.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="https://www.w3.org/2001/XMLSchema" 
targetNamespace="https://www.journaldev.com/Employee" 
xmlns:empns="https://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>

Notice that above XSD contains two root element and namespace also, I have created two sample XML file from XSD using Eclipse.

注意,上面的XSD还包含两个根元素和名称空间,我已经使用Eclipse从XSD创建了两个示例XML文件

EmployeeRequest.xml

EmployeeRequest.xml

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

EmployeeResponse.xml

EmployeeResponse.xml

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

Here is another XML file that doesn’t confirms to the Employee.xsd.

这是另一个未向Employee.xsd确认的XML文件。

employee.xml

employee.xml

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

Here is the program that is used to validate all three XML files against the XSD. The validateXMLSchema method takes XSD and XML file as argument and return true if validation is successful or else returns false.

这是用于针对XSD验证所有三个XML文件的程序。 validateXMLSchema方法将XSD和XML文件作为参数,如果验证成功,则返回true ,否则返回false

XMLValidation.java

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;
    }
}

Output of the above program is:

上面程序的输出是:

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

The benefit of using Java XML validation API is that we don’t need to parse the file and there is no third party APIs used.

使用Java XML验证API的好处是我们不需要解析文件,并且不使用任何第三方API。

翻译自: https://www.journaldev.com/895/how-to-validate-xml-against-xsd-in-java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值