我想验证一个 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 的方法吗?
最佳答案
您必须定义一个 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);
关于java - 使用 java 针对两个模式验证 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915742/