我正在将 XML 文件解码为 JAXB 生成的 Java 对象。我希望解码器在此过程中根据模式验证文件。架构的 .xsd
文件位于依赖项 .jar
文件内。我像这样设置架构:
ClassLoader classLoader = getClass().getClassLoader();
InputStream schemaStream = classLoader.getResourceAsStream(schemaFilePath);
StreamSource schemaSource = new StreamSource(schemaStream);
Schema schema = factory.newSchema(schemaSource);
unmarshaller.setSchema(schema);
除一个问题外,大多数情况下都有效。该架构将一些复杂类型分解到其他 .xsd
文件中。解码器似乎无法找到分解的 .xsd
文件,因为当我尝试设置架构时,我收到 SAXException
:
Cannot resolve the name 'tns:FactoredOutType' to a(n) 'type definition' component.
注意:当从 eclipse 运行时,当它引用 target
文件夹中的 .xsd
文件而不是 .jar
文件时,这可以正常工作。
有人知道如何让分解的 .xsd
文件适用于依赖项的 .jar
文件中的架构吗?
编辑:
如果它是有用的信息,顶级 .xsd
位于 model
文件夹中,并且它引用的类型位于 model/common
中,因此我将顶级 .xsd
引用为:
"model/TopLevel.xsd"
...在其中,它引用分解的 .xsd
为:
"common/FactoredOut.xsd"
最佳答案
我最终通过将对 newSchema
的调用从传递 StreamSource
切换为传递 URL
来解决这个问题,这保留了基本 URI,因此仍然可以找到包含的类型(正如 @PetruGardea 在他的评论中提到的那样)。结果代码如下所示:
URL schemaURL = objectType.getClassLoader().getResource(schemaPath);
if (schemaURL != null) {
Schema schema = factory.newSchema(schemaURL);
unmarshaller.setSchema(schema);
}
感谢大家的帮助!
关于java - 如何使用资源 jar 中分解出的 .xsd 文件来指定 JAXB 架构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32852192/