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 ?
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".