使用 JAXB 和 Stax 进行验证以编组 XML 文档
我创建了一个 XML 模式 (foo.xsd) 并使用 xjc 为 JAXB 创建绑定类。假设根元素是collection
,我正在编写N个document
对象,它们是复杂类型。
因为我计划写出大型 XML 文件,所以我使用 Stax 写出 collection
根元素,并使用 JAXB 使用 Marshaller.marshal(JAXBElement, XMLEventWriter)
。这是jaxb 的非官方用户指南推荐的方法。
我的问题是,如何在编组 XML 时验证它?如果我将模式绑定到 JAXB 编组器(使用 Marshaller.setSchema()
),我会收到验证错误,因为我只编组子树(它抱怨它没有看到 集合 root 元素”)。我想我真正想做的是将架构绑定到
Stax XMLEventWriter
或类似的东西。
对这个整体方法的任何评论都会有所帮助。基本上我想成为能够使用 JAXB
编组和解组大型 XML 文档,而不会耗尽内存,因此如果有更好的方法来执行此操作,请告诉我。
I have created an XML schema (foo.xsd) and used xjc
to create my binding classes for JAXB. Let's say the root element is collection
and I am writing N document
objects, which are complex types.
Because I plan to write out large XML files, I am using Stax to write out the collection
root element, and JAXB to marshal document subtrees using Marshaller.marshal(JAXBElement, XMLEventWriter)
. This is the approach recommended by jaxb's unofficial user's guide.
My question is, how can I validate the XML while it's being marshalled? If I bind a schema to the JAXB marshaller (using Marshaller.setSchema()
), I get validation errors because I am only marshalling a subtree (it's complaining that it's not seeing the collection
root element"). I suppose what I really want to do is bind a schema to the Stax XMLEventWriter
or something like that.
Any comments on this overall approach would be helpful. Basically I want to be able to use JAXB
to marshal and unmarshal large XML documents without running out of memory, so if there's a better way to do this let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一些 Stax 实现似乎能够验证输出。请参阅以下类似问题的答案:
将 Stax2 与 Woodstox 结合使用
Some Stax implementations seem to be able to validate output. See the following answer to a similar question:
Using Stax2 with Woodstox
仅当 Marshaller 调用
Iterator.next()
时,您才可以使根集合惰性化并实例化项目。然后,对marshal()
的一次调用将生成一个巨大的经过验证的 XML。您不会耗尽内存,因为已经序列化的 bean 会被 GC 收集。另外,如果需要有条件地跳过,可以将
null
作为集合元素返回。不会有NPE。即使在巨大的 XML 上,XML 模式验证器本身似乎也消耗很少的内存。
请参阅 JAXB 的 ArrayElementProperty.serializeListBody()
You can make your root collection lazy and instantiate items only when the Marshaller calls
Iterator.next()
. Then a single call tomarshal()
will produce a huge validated XML. You won't run out of memory, because the beans that are already serialized get collected by GC.Also, it's OK to return
null
as a collection element if it needs to be conditionally skipped. There won't be NPE.The XML schema validator itself seems to consume little memory even on huge XMLs.
See JAXB's ArrayElementProperty.serializeListBody()