如何在 Java 中针对 XSD 1.1 验证 XML? [英] How to validate XML against XSD 1.1 in Java?

查看:25
本文介绍了如何在 Java 中针对 XSD 1.1 验证 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to validate XML files against XML Schema 1.1 in Java?

我从这个教程中获取了代码更改了查找工厂的行以使用 XML Schema 1.1,正如我在 Xerces 常见问题解答.

I took the code from this tutorial and changed the line where it looks up the factory to use XML Schema 1.1 as I have seen in this code example from the 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 常见问题解答中的代码片段完全相同.我什至尝试将 Xerces 添加到我的 Maven 依赖项中,但这也无济于事.

As I see it I have exactly the same imports as the code snippet in the Xerces FAQ. I even tried to add Xerces to my Maven dependencies but that didn't help either.

干杯:)

推荐答案

我认为您不能使用 JAXP 服务机制来搜索 XSD 1.1 处理器.以正常方式加载 Saxon 或 Xerces,然后启用 XSD 1.1 处理.对于撒克逊人,这是使用

I don't think you can use the JAXP service mechanism to search for an XSD 1.1 processor. Load Saxon or Xerces in the normal way, and then enable XSD 1.1 processing. For Saxon this is done using

SchemaFactory.setProperty("http://saxon.sf.net/feature/xsd-version", "1.1")

UPDATE 2021-09-04 在最近的 Saxon 版本中,XSD 1.1 是默认值,无需设置特殊属性即可启用它.

UPDATE 2021-09-04 In recent Saxon releases, XSD 1.1 is the default, and no special property needs to be set to enable it.

这篇关于如何在 Java 中针对 XSD 1.1 验证 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆