在 Java 中根据 XSD 验证 XML / 获取 schemaLocation
如何在 Java 中使用 XSD 验证 XML 文件?我们事先不知道架构。我希望能够获取 schemaLocation、下载 XSD、缓存它,然后执行实际验证。
问题是,使用 javax.xml.parsers.DocumentBuilder
/DocumentBuilderFactory
类,我似乎无法掌握 schemaLocation
代码>提前。这有什么技巧呢?我应该研究哪些课程?
也许有更合适的 API 我可以使用?整个问题是我们需要动态验证,而(不一定)在本地拥有 XSD。
如何获取 XSD 文件中定义的 schemaLocation
的 URL?
我知道您可以设置功能/属性,但这是另一回事。我需要首先从 XSD 获取 schemaLocation
。
请指教!
How can one validate an XML file using an XSD in Java? We don't know the schema in advance. I would like to be able to get the schemaLocation
, download the XSD, cache it and then perform the actual validation.
The problem is, that with javax.xml.parsers.DocumentBuilder
/DocumentBuilderFactory
classes I can't seem to be able to get a hold of the schemaLocation
in advance. What's the trick for this? Which classes should I look into?
Perhaps there's a more suitable API I can use? The whole problem is that we need to validate dynamically, without (necessarily) having the XSDs locally.
How could one get a hold of the URL of schemaLocation
defined in the XSD file?
I know you can set features/attributes, but that's a different thing. I need to get the schemaLocation
from the XSD first.
Please advise!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
鉴于您使用的是 Xerces(或 JDK 默认值),您是否尝试在工厂中将此功能设置为 true: http://apache.org/xml/features/validation/schema。您还可以使用有关架构的其他功能: http://xerces.apache.org /xerces2-j/features.html
更新 2(用于缓存):
实现 org.w3c.dom.ls.LSResourceResolver 并将其设置在
SchemaFactory
使用setResourceResolver
方法。该解析器将从缓存中获取模式,或者从位置引用的任何位置获取模式。更新 3:
LSResourceresolver 示例(我认为这对您来说将是一个很好的起点):
MyLSInput 的实现确实很无聊:
Given that you are using Xerces (or JDK default), have you tried setting this feature to true on the factory: http://apache.org/xml/features/validation/schema. There are other features that you can play with regarding schemas: http://xerces.apache.org/xerces2-j/features.html
UPDATE 2 (for caching):
Implement a
org.w3c.dom.ls.LSResourceResolver
and set this on theSchemaFactory
using thesetResourceResolver
method. This resolver would either get the schema from cache or fetch it from wherever the location refers to.UPDATE 3:
LSResourceresolver example (which I think will be a good starting point for you):
The implementation of MyLSInput is really boring: