简体   繁体   中英

Why element creation requires the document object in DOM?

As noted by others , in Java, with the default W3C DOM libraries, one is required to use the Document object a factory to elements, ie:

 import org.w3c.dom.Document;
 import org.w3c.dom.Element;

 Document d;
 Element e;

 e = d.createElement("tag");

Why is that necessary? Why conceptually a method can't create an XML element without knowing all of the target document? Why I can't just instantiate using 'new' or something to that effect?

Because the DOM API is heavily interface-based. Document and Element are both interfaces, implemented by the various implementations of the API. As a result, you can't just instantiate the Element, since you don't know which implementation to use. All node creation must be therefore be done using factory methods. That was a design choice made by the DOM API designers.

If you want a DOM API that's easier to live with, try XOM , JDOM or DOM4J .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM