tags:

views:

854

answers:

2

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");

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");

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.

+6  A: 

Element extends Node, and Node defines getOwnerDocument, so you could do something like this:

e2 = e.getOwnerDocument().createElement("tag");

http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html#getOwnerDocument%28%29

rjohnston
awesome, i knew there had to be something simple i was missing, thanks
Mike
A: 

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.

peter.murray.rust