使用 Java 根据本地 DTD 文件验证 XML 文件
如何根据本地存储为文件的 DTD 验证 XML 文件? XML 文件没有任何 DOCTYPE 声明(或者可能有一个应该被覆盖的声明)。 我查看了这个线程 但除了他们使用 .NET 的事实之外,我怀疑这是否是一个好的解决方案。
任何意见表示赞赏!
How can I validate an XML file against a DTD that is stored locally as a file? The XML file does not have any DOCTYPE declaration (or may have one that should then be overridden). I had a look at this thread but besides the fact they are using .NET I doubt that this is a good solution.
Any input appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在理想的情况下,您可以使用 验证器。 像这样的事情:
不幸的是,Sun 实现(至少从 Java 6 开始)不支持从 DTD 创建 Schema 实例。 您也许能够找到第三方实施。
您最好的选择可能是在使用其他机制进行解析之前更改文档以包含 DTD。
您可以使用转换器插入 DTD 声明:
...但这似乎并没有取代现有的 DTD 声明。
这个 StAX 事件阅读器可以完成工作:
它将在文档开始后立即发送给定的 DTD 声明,并丢弃旧文档中的任何声明。
演示用法:
请注意,XMLEventReader 可以形成执行验证的某些其他转换机制的源。
如果您有该选项,那么使用 W3 模式进行验证会容易得多。
In an ideal world, you'd be able to validate using a Validator. Something like this:
Unfortunately, the Sun implementation (at least, as of Java 6) does not include support for creating a Schema instance from a DTD. You might be able to track down a 3rd party implementation.
Your best bet may be to alter the document to include the DTD before parsing using some other mechanism.
You can use a transformer to insert a DTD declaration:
...but this does not seem to replace an existing DTD declaration.
This StAX event reader can do the job:
It will send a given DTD declaration right after the document start and discard any from the old document.
Demo usage:
Note that the XMLEventReader could form the source for some other transformation mechanism that performed validation.
It would be much easier to validate using a W3 schema if you have that option.
我很确定前面提到的东西会起作用..
如果问题是您希望根据您的 dtd 而不是作者对其进行验证,您应该确保有明确的文档详细说明 doctype 以及 xml 文件中必须包含的内容
im pretty sure the stuff aforementioned will work..
if the problem is you want it to be validated against your dtd rather than the authors you should ensure that there is clear documentation that details the doctype, and what must be in the xml file
您必须实现
EntityResolver
,请查看此示例< /a>.You have to implement the
EntityResolver
, checkout this example.