Java:从元素而不是文档创建 DOM 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1391687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Create DOM Element from Element, not Document
提问by Mike
As you know, the proper way to create a Dom Element in Java is to do something like this.
如您所知,在 Java 中创建 Dom 元素的正确方法是执行以下操作。
import org.w3c.dom.Document;
import org.w3c.dom.Element;
Document d;
Element e;
e = d.createElement("tag");
You need to use d to generate the element because it needs a document context. (I'm not 100% sure why, but maybe misunderstanding this is part of my problem)
您需要使用 d 来生成元素,因为它需要一个文档上下文。(我不是 100% 确定为什么,但也许误解这是我的问题的一部分)
What I don't understand is, why you can't do something like this
我不明白的是,为什么你不能做这样的事情
Element e;
Element e2;
e2 = e.createElement("anothertag");
Since e already has the context of d, why can't I create another element from an element? It would certainly simplify my design not having to keep a reference to the Document everywhere.
既然 e 已经有了 d 的上下文,为什么我不能从一个元素创建另一个元素?它肯定会简化我的设计,而不必在任何地方保留对文档的引用。
采纳答案by rjohnston
Element extends Node, and Node defines getOwnerDocument, so you could do something like this:
Element 扩展了 Node,Node 定义了 getOwnerDocument,所以你可以这样做:
e2 = e.getOwnerDocument().createElement("tag");
http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html#getOwnerDocument()
http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html#getOwnerDocument()
回答by peter.murray.rust
I spent far too long wrestling with this problem of the Document in the W3C DOM. The concept of an owner document also as factory (createElement(...)) is restricting. If you are not required to use the W3C DOM I would change to the Open Source XOM (http://www.xom.nu). This was developed to be simpler and more flexible than W3C (e.g. you can subclass Element and Document has only a minor role). XOM does not require a Document unless you want to serialize. One thing that immediately becomes simpler is moving Elements around between different trees.
我花了很长时间来解决 W3C DOM 中文档的这个问题。所有者文档也作为工厂 (createElement(...)) 的概念是有限制的。如果您不需要使用 W3C DOM,我将更改为 Open Source XOM ( http://www.xom.nu)。这被开发为比 W3C 更简单和更灵活(例如,您可以子类化 Element 和 Document 仅具有次要作用)。除非您想序列化,否则 XOM 不需要文档。立即变得更简单的一件事是在不同的树之间移动元素。