【问题标题】:XML Validation - Using multiple xsd'sXML 验证 - 使用多个 xsd
【发布时间】:2011-10-23 23:16:01
【问题描述】:

我有两个 xsd 文件来验证 xml。但问题是我的代码只需要一个 xsd。下面代码中如何使用其他xsd?我不知道应该在哪里放置/调用第二个 xsd 文件。

             private void validate(File xmlF,File xsd1,File xsd2) {
                    try {
                        url = new URL(xsd.toURI().toString());//  xsd1
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }


                    source = new StreamSource(xml); // xml
                    try {
                        System.out.println(url);
                        schema = schemaFactory.newSchema(url);
                    } catch (SAXException e) {
                        e.printStackTrace();
                    }
                    validator = schema.newValidator();
                    System.out.println(xml);
                    try {
                        validator.validate(source);
                    } catch (SAXException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

【问题讨论】:

  • 您是否已经尝试过newSchema(Source[])
  • 是的。我试过这样。它不起作用,可能是因为 Source[] 用于 xml。我们无法将 xsd 类型转换为源代码。
  • 与上一个有关此 XML 验证项目的问题一样,我想向您指出 SSCCE。您的代码 sn-p 远未完成,因为您在此方法之外定义变量等。注意您提出问题的方式有助于我们为您提供帮助。

标签: java xml validation


【解决方案1】:

在 SO 或 Google 上搜索时获得大量点击。其中一个是this问题,作者在其中找到了自己的解决方案,并报告了以下代码以将多个xsd添加到验证器:

Schema schema = factory().newSchema(new Source[] {
  new StreamSource(stream("foo.xsd")),
  new StreamSource(stream("Alpha.xsd")),
  new StreamSource(stream("Mercury.xsd")),
});

但是,当直接在 StreamSource 上使用 InputStream 时,解析器无法加载任何引用的 XSD 文件。例如,如果文件xsd1 导入或包含第三个文件(不是xsd2),则模式创建将失败。您应该设置系统标识符 (setSystemId) 或(甚至更好)使用 StreamSource(File f) 构造函数。

根据您的示例代码调整:

try {
  schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  schema = schemaFactory.newSchema(new Source[] {
    new StreamSource(xsd1), new StreamSource(xsd2)
  });
} catch (SAXException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

注意:

如果使用类路径资源,我更喜欢StreamSource(String systemId) 构造函数(而不是创建File):

new StreamSource(getClass().getClassLoader().getResource("a.xsd").toExternalForm());

【讨论】:

  • 这和我上面的问题一模一样。
  • 这与您在评论中提供的解决方案相同。这就是为什么我赞成你的评论。 OP 在实现它时遇到了麻烦;我已经在我的 Eclipse 中准备好代码,以回答他之前的问题,然后简单地对其进行调整以显示如何使用 Source[]。我希望没有难过的感觉?
  • @Michael-O 这就是为什么你应该把它作为答案发布,而不是评论
  • new StreamSource(getClass().getClassLoader().getResource("a.xsd").toExternalForm()) 解决了我的问题,谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-02-19
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 2023-01-29
相关资源
最近更新 更多