“即时"编辑大型 xml 文件 [英] Editing a large xml file 'on the fly'

查看:29
本文介绍了“即时"编辑大型 xml 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 xml 文件存储在数据库 blob 中,用户将通过 spring/hibernate web 应用程序下载该文件.在通过 Hibernate 作为 byte[] 检索它之后,但在将其发送到输出流之前,我需要编辑 XML 的某些部分(具有两个子节点和一个属性的单个节点).

I've got an xml file stored in a database blob which a user will download via a spring/hibernate web application. After it's retrieved via Hibernate as a byte[] but before it's sent to the output stream I need to edit some parts of the XML (a single node with two child nodes and an attribute).

我担心的是,如果文件更大(有些是 40mb+),那么我真的不想通过将整个文件保存在内存中、编辑它然后通过输出流将其传递给用户来做到这一点.有没有办法即时"编辑它?

My concern is if the files are larger (some are 40mb+) then I don't really want to do this by having the whole file in memory, editing it and then passing it to the user via the output stream. Is there a way to edit it 'on the fly' ?

byte[] b = blobRepository.get(blobID).getFile();
// What can I do here?
ServletOutputStream out = response.getOutputStream();
out.write(b);

推荐答案

您可以使用 SAX 流.

You can use a SAX stream.

使用 SAX 框架解析文件,当您的处理程序接收到 SAX 事件时,将未更改的项目传回构建 XML 输出的 SAX 处理程序.

Parse the file using the SAX framework, and as your Handler receives the SAX events, pass the unchanged items back out to a SAX Handler that constructs XML output.

当您到达要更改的部分"时,您的中介类会读入不需要的事件,并写出想要的事件.

When you get to the "part to be changed", then your intermediary class would read in the unwanted events, and write out the wanted events.

这样做的好处是不需要将整个文件作为中间表示(比如 DOM)保存在内存中;但是,如果转换很复杂,您可能必须缓存许多项目(文档的部分),以便让它们可用于重新排列的输出.一个足够复杂的转换(一个可以做任何事情的转换)最终会变成 DOM 的开销,但是如果您知道自己忽略了文档的很大一部分,则可以节省大量内存.

This has the advantage of not holding the entire file in memory as an intermediate representation (say DOM); however, if the transformation is complex, you might have to cache a number of items (sections of the document) in order to have them available for rearranged output. A complex enough transformation (one that could do anything) eventually turns into the overhead of DOM, but if you know you're ignoring a large portion of your document, you can save a lot of memory.

这篇关于“即时"编辑大型 xml 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆