问题描述
如你所知,在Java中创建Dom Element的正确方法是做这样的事情。
As you know, the proper way to create a Dom Element in Java is to do something like this.
import org.w3c.dom.Document;
import org.w3c.dom.Element;
Document d;
Element e;
e = d.createElement("tag");
您需要使用d生成元素,因为它需要一个文档上下文。 (我不是100%肯定为什么,但也许误会这是我的问题的一部分)
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)
我不明白的是,为什么你不能做某事像这样
What I don't understand is, why you can't do something like this
Element e;
Element e2;
e2 = e.createElement("anothertag");
由于e已经具有d的上下文,为什么我不能从元素创建另一个元素?
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.
推荐答案
元素扩展Node,Node定义getOwnerDocument ,所以你可以这样做:
Element extends Node, and Node defines getOwnerDocument, so you could do something like this:
e2 = e.getOwnerDocument().createElement("tag");
这篇关于Java:从元素创建DOM元素,而不是文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!