tags:

views:

58

answers:

1

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

 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?

+4  A: 

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.

skaffman
I would've answered "because the DOM API is badly designed..." but I guess yours is more thorough :) It's one of those API:s where they've crammed in every single design pattern without apparently really understanding them.
Esko
It's pretty awful, yes, but thankfully we can usually use one of the alternatives.
skaffman
The question that follows then is why CreateElement() isn't static?
maayank
Because interface methods cannot be static. ;)
Lucero
@maayank: If it were static, it would have to go on the class that implements `Document` - and you don't know what that class is.
skaffman
obviously you guys are correct... tnx :)
maayank