java xsd验证xml,如何在Java中针对XSD 1.1验证XML?

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

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.

This is my code:

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

}

}

}

The code throws this exception:

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

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.

Cheers :)

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值