本文介绍了如何使用Java DOM克隆整个文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种可靠的,独立于实现的克隆整个文档的方式。 Javadoc具体说,在Document上调用cloneNode是特定于实现的。我已经尝试通过一个无操作变压器传递文档,但结果节点没有所有者文档。

I'm looking for a reliable, implementation-independent way to clone an entire Document. The Javadocs specifically say that calling cloneNode on a Document is implementation-specific. I've tried passing the Document through a no-op Transformer, but the resulting Node has no owner Document.

我可以创建一个新的文档,并从旧的,但恐怕可能会有一些文档元数据丢失。将文档写入字符串并将其解析为相同的东西。

I could create a new Document and import the nodes from the old one, but I'm afraid there might be bits of Document metadata that get lost. Same thing with writing the Document to a string and parsing it back in.

任何想法?

由方式,我被困在Java 1.4.2,由于我无法控制的原因。

By the way, I'm stuck at Java 1.4.2, for reasons beyond my control.

推荐答案

由于一些评论指出,序列化和重新解析文档有问题。除了内存使用,性能考虑和规范化之外,还有prolog(DTD或模式)的丢失,注释的潜在丢失(不需要被捕获),以及可能是重要的空格的丢失。应该避免序列化。

As some of the comments point out, there are problems with serializing and re-parsing a document. In addition to memory usage, performance considerations, and normalization, there's also loss of the prolog (DTD or schema), potential loss of comments (which aren't required to be captured), and loss of what may be significant whitespace. Serialization should be avoided.

如果真正的目标是制作一个现有的DOM Document对象的副本,那么它应该以编程方式在内存中处理。感谢您使用Java 5中提供的功能或使用外部XSLT库(如Xalan)进行此操作是一种相对简单的方式,这是一种直接转换。

If the real goal is to make a copy of an existing DOM Document object, then it should be handled programmatically, in memory. Thanksfully there is a relatively easy way to do this using features available in Java 5 or using external XSLT libraries like Xalan, which is to a a pass-through transformation.

下面是显示了Java 5解决方案:

Below is shown the Java 5 solution:

TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer tx   = tfactory.newTransformer();
DOMSource source = new DOMSource(doc);
DOMResult result = new DOMResult();
tx.transform(source,result);
return (Document)result.getNode();

基本上是这样您需要处理异常,并且可能希望配置变压器,但我将其作为读者的练习。

That's basically it. You'll need to handle exceptions and may wish to configure the transformer, but I leave that as an exercise for the reader.

这篇关于如何使用Java DOM克隆整个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 06:59