gpt4 book ai didi

java - 如何在 Java 中针对 XSD 1.1 验证 XML?

转载 作者:太空狗 更新时间:2023-10-29 22:53:00 25 4
gpt4 key购买 nike

在 Java 中根据 XML Schema 1.1 验证 XML 文件的最佳方法是什么?

我从这个 tutorial 中获取了代码并将查找工厂的行更改为使用 XML Schema 1.1,正如我在 Xerces FAQ 的代码示例中看到的那样.

这是我的代码:

import java.io.File;
import java.io.IOException;
import javax.xml.transform.Source;
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 XSDValidator {
private static void validateFile(File xmlFile, File xsdFile) throws SAXException, IOException
{
// 1. Lookup a factory for the W3C XML Schema language
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1");
// SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

// 2. Compile the schema.
File schemaLocation = xsdFile;
Schema schema = factory.newSchema(schemaLocation);

// 3. Get a validator from the schema.
Validator validator = schema.newValidator();

// 4. Parse the document you want to check.
Source source = new StreamSource(xmlFile);

// 5. Check the document
try
{
validator.validate(source);
System.out.println(xmlFile.getName() + " is valid.");
}
catch (SAXException ex)
{
System.out.println(xmlFile.getName() + " is not valid because ");
System.out.println(ex.getMessage());
}
}
}

代码抛出异常:

java.lang.IllegalArgumentException: No SchemaFactory that implements the schema language specified by: http://www.w3.org/XML/XMLSchema/v1.1 could be loaded

在我看来,我的导入与 Xerces FAQ 中的代码片段完全相同。我什至尝试将 Xerces 添加到我的 Maven 依赖项中,但这也无济于事。

干杯:)

最佳答案

不幸的是,JDK 捆绑版本(从 Java 8 开始)和 maven central (2.11.0) 的最新官方版本都不包含 XSD 1.1 实现。

您实际上需要 Xerces 的 2.11.0-xml-schema-1.1-beta 版本才能运行您所链接的常见问题解答中的示例。

您可以执行以下操作之一。

  1. 从 Xerces 网站下载 Xerces2 Java 2.11.0 (XML Schema 1.1)(测试版) 二进制文件并手动将 jar 添加到类路径(或通过 Maven 在本地安装)。链接:http://xerces.apache.org/mirrors.cgi .您至少需要以下内容:

    cupv10k-runtime.jar
    org.eclipse.wst.xml.xpath2.processor_1.1.0.jar
    xercesImpl.jar
    xml-apis.jar
  2. 使用以下非官方 maven 依赖项。

    <dependency>
    <groupId>org.opengis.cite.xerces</groupId>
    <artifactId>xercesImpl-xsd11</artifactId>
    <version>2.12-beta-r1667115</version>
    </dependency>

关于java - 如何在 Java 中针对 XSD 1.1 验证 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20807066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com