[jdom-interest] Reusable JDOM Elements

Hallvard Trætteberg hal at idi.ntnu.no
Tue Nov 12 01:13:21 PST 2002


> interesting. It looks like XMLOuputter is purley
> recursive. If you subclass the elements that will
> be the parent to the cached sub-trees, I guess you
> could 'divert' XMLOutputter down the cached sub-tree
> by overriding the getContent() method.

Personally, I would subclass XMLOutputter and let it do the mapping, if
possible. That may make it easier to clean up afterwards. But as your
example shows, it works!

An interesting generalization is to let Diverter constructor take a context
node and an XPath, and let getContent apply the xpath to the context node.
The context node could for instance be a large document of relevant cached
sub-trees and the xpath would select the appropriate one. With a
VariableContext with interesting bindings, e.g. $source bound to the
Diverter itself, you could select a sub-tree depending on attributes of the
Diverter, something like new XPath(sub-tree[@name=$div/@tree-name]). Just
make sure the XPath doesn't call getContent recursively!

> Concerning caching sub-trees:
> in a potentially busy server environment, I preconstruct and cache
> potentially many JDOM subtrees. Comes usage time, the subtree gets
> cloned and attached to a real Document, which is subsequently output to
> XML and sent out.
> It appears wasteful to have to clone the Elements, even if they are not
> going to be changed, for the sole reason that they maintain a reference
> to their parent.  It seems also to be slightly convoluted to manage
> recycling of such subtrees.
> Is there a good pattern or solution out there (JDOM or closely related)
> which allows me to build Document trees, which are only top-to-bottom
> connected or which allows to reuse the constant subtree(s) easily?
> The main problem with parentless JDOM elements is traversal, i.e. which
> parent should you navigate to when going up in a tree. However,
> sometimes your algorithm won't traverse upwards, which might be the case
> for outputting XML into a stream. This depends on how XMLOutputter
> works. One way is to make the traversing/visiting function map from an
> element to an alternative one, and proceed with the alternative Element,
> something like:
> - make a hashtable which maps from Element to Element
> - build your cache of Element trees
> - add leaf Element nodes to your document as placeholders for the trees
> - put placeholder, tree pairs in the hashtable
> - subclass XMLOutputter (if possible) and before outputting a child,
> include something like
> if (treemap.haskey(child)) child = treemap.get(child)
> I'm not sure XMLOutputter is easy to subclass like this, but the trick
> at least has worked for me in other cases. I've even included a map for
> the other direction, so I can traverse the other way, from sub-tree to
> parent.
> Hallvard

More information about the jdom-interest mailing list