Why does creating a element require a document object in the DOM?

As noted by others , in Java, with the W3C default DOM libraries, you need to use the Document a factory object for elements, that is:

import org.w3c.dom.Document; import org.w3c.dom.Element; Document d; Element e; e = d.createElement("tag"); 

Why is this necessary? Why conceptually a method cannot create an XML element without knowing the entire target document? Why can't I just create an instance using "new" or something like that?

+4
source share
1 answer

Because the DOM API is heavily interface based. Document and Element are both interfaces implemented by various API implementations. As a result, you cannot just instantiate the element, because you do not know which implementation to use. Therefore, node creation must be done using factory methods. It was a design choice made by the DOM API developers.

If you need a DOM API that is easier to live with, try XOM , JDOM, or DOM4J .

+4
source

Source: https://habr.com/ru/post/1305960/


All Articles