使用Java中的Xerces对XSD 1.1进行XML验证

时间:2013-12-28 20:32:20

标签: java xml validation xerces xsd-1.1

我已经通过Maven安装了Xerces:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jdom</groupId>
        <artifactId>jdom</artifactId>
        <version>2.0.2</version>
    </dependency>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
    </dependency>            
</dependencies>

然后,我尝试了Xerces FAQ中此示例中给出的代码,以针对1.1版中的模式验证XML文件。这是我的代码:

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");

    // 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
at javax.xml.validation.SchemaFactory.newInstance(SchemaFactory.java:204)
at example.xml.XSDValidator.validateFile(XSDValidator.java:65)

似乎我无法正确配置/安装Xerces。请帮我搞定这个,XML文件强迫我使用1.1中的模式,我有一个正常的1.0运行验证器,但我有很大的问题。我很欣赏每一个提示!

3 个答案:

答案 0 :(得分:6)

看起来你需要Xerces2 Java 2.11.0(XML Schema 1.1)(Beta)版本,它不在maven资源库中。您可以从Xerces网站下载它,并将其安装到您当地的maven存储库: mvn install:install-file -Dfile=xercesImpl.jar -DgroupId=xerces -DartifactId=xercesImpl -Dversion=2.11.0.beta -Dpackaging=jar 然后,您将能够将其包含在Maven项目依赖项中:

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0.beta</version>
</dependency>   

答案 1 :(得分:5)

我会添加另一个答案,因为对我来说这种依赖不起作用(与OP描述的错误相同):

<dependency>
  <groupId>xerces</groupId>
  <artifactId>xercesImpl</artifactId>
  <version>2.11.0</version>
</dependency>

我认为2.11.0应该比2.11.0.beta更新,但似乎该版本不支持xsd1.1!

相反,只有以下依赖项才能为我提供有效的XSD1.1验证:

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

(在此SO帖子中找到:How to validate XML against XSD 1.1 in Java?

答案 2 :(得分:1)

我认为他们现在已经将版本2.11添加到了maven。 Maven中的以下依赖项是开箱即用的:

C:\temp\From\Test_This Space.txt