且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Java DOM克隆整个文档?

更新时间:2023-12-05 15:19:04

由于一些评论指出,序列化和重新解析文档有问题。除了内存使用,性能考虑和规范化之外,还有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.