0

我想验证一个 xml 文件,该文件在根元素中给出了架构位置,而没有本地文件。我想我让它工作了,但问题是这个 xml 包含另一个模式,它位于 xml 文件中的另一个元素上,我找不到一种方法来定义模式来验证单个文件。有人可以在这里帮助我吗?

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new URL(UrlToSchema));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(xmlFile));

还有一种从 xml 文件中获取变量 UrlToSchema 的方法吗?

4

1 回答 1

0

您必须定义一个数组StreamSource以包含 xml 模式列表。你可以参考javadoc

假设有两个 xml 模式,即 xsds,代码应该看起来像这样

    StreamSource[] xsdSources = new StreamSource[2]; 
    FileInputStream fis1 = new FileInputStream("schema1.xsd"); 
    sources[0] = new StreamSource(fis1); 
    FileInputStream fis2 = new FileInputStream("schema2.xsd"); 
    sources[1] = new StreamSource(fis2); 
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
    Schema schema = schemaFactory.newSchema(xsdSources);
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(xmlFile)); 

在您的情况下,要从 ulr 中读取,您可以使用以下代码。

InputStream fis1 = new URL("http://www.somesite.com/schema1.xsd").openStream();
sources[0] = new StreamSource(fis1); 
于 2019-11-18T13:50:09.730 回答