如何在Java中根据XSD 1.1验证XML?
2022-09-03 00:46:39
在 Java 中根据 XML Schema 1.1 验证 XML 文件的最佳方法是什么?
我从本教程中获取了代码,并将其查找工厂的行更改为使用 XML 架构 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依赖项中,但这也没有帮助。
干杯:)