Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Create DOM Element from Element, not Document

Tags:

java

dom

xml

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.

like image 682
Mike Avatar asked Sep 08 '09 02:09

Mike


People also ask

How do you add an element to the DOM?

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.

How do I convert an element to a document?

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

What is getDocumentElement in Java?

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.


2 Answers

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()

like image 106
rjohnston Avatar answered Sep 24 '22 13:09

rjohnston


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.

like image 38
peter.murray.rust Avatar answered Sep 22 '22 13:09

peter.murray.rust