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.
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
Element element = //code to get a element Node node = //code to get a node //document from Node Document document = node. getOwnerDocument(); //document from a Element Document document = element. getOwnerDocument();
getDocumentElement() This method searches an XML object for the DOM document element (or "root" node). It creates an XML object containing the document element and all child elements from an XML object or XML string.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With