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 ?
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 particularDocument
. So you're already using the correct approach by creating an empty document from theDocumentBuilder
.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 returnedElement
to their ownDocument
they will first have to "adopt" it by callingadoptNode
, as aDocument
is only allowed to contain nodes that it "owns".