How can I create a DOM Element without a document?

6.3k views Asked by At

Working with JAXP, the "Hello world" to create an element is:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();

Element e = doc.createElement("helloElement");
// attributes, append, etc...

this makes the creation of an Element dependent of a document object. Is there any way to create an element without a particular document ? something like:

Element e = DomDocument.createElement("helloElement"); //static method or so ...
return e;

Implementing the Element interface is way too much than necessary!

the purpose is to get a DOM Element from a POJO without the need to pass a document any suggestions ?

2

There are 2 answers

0
Ian Roberts On BEST ANSWER

Is there any way to create an element without a particular document?

No. The way the DOM is designed the Document is a factory for all the other objects, and those objects can only exist within the context of a particular Document. So you're already using the correct approach by creating an empty document from the DocumentBuilder.

the purpose is to get a DOM Element from a POJO without the need to pass a document

You can create your own Document within the POJO and use that to create elements, but then if a caller of your method wants to add the returned Element to their own Document they will first have to "adopt" it by calling adoptNode, as a Document is only allowed to contain nodes that it "owns".

1
Greg Brown On

Looks like Node (which Element extends) provides a getOwnerDocument() method. Presumably you'd want to add new elements to an existing element, so you could use this method to get a reference to the parent element's document and create the new element from there.