[XML-SIG] Building a DOM tree

Andrew M. Kuchling akuchlin@cnri.reston.va.us
Thu, 25 Mar 1999 12:15:45 -0500 (EST)


Jeff.Johnson@icn.siemens.com writes:
>I don't know that much about the inner working of Python so this may be a
>dumb question.  How and when would the global dictionary be released?  Is
>removeChild called for all nodes when I dereference a DOM document node?

	Ooh, good catch, Jeff.  With the current CVS implementation,
the dictionary is discarded when the document node gets collected, but
cleaning out the global dictionary is harder.  DocumentFragments and
Documents would need a __del__ method that walked over their children
and deleted the dictionary entries, slowing down destruction.  Will
the speedup from removing proxies compensate for it?  More hmmm...

>Also, I have gotten bitten several times by the fact that I can't move a
>node from one tree to another.  I figured cloneNode() would allow it but it

	A good observation; the DOM Level 1 doesn't actually say
whether the result of cloneNode() is associated with the same document
or not.  I'd suspect the answer is 'yes', but have written to the
www-dom list asking about this.

	Moving things between DOM document trees doesn't seem possible
with the DOM Level 1 specification; all the functions to add and
remove children from a node can raise a WRONG_DOCUMENT exception,
which is described as:

WRONG_DOCUMENT_ERR: Raised if newChild was created from a different
                    document than the one that created this node.

	DocumentFragments should be used for this, I think.  Create
lots of DocumentFragments, and build your various small trees
underneath them.  To output them, make a copy of the document fragment 
(to avoid it being destroyed) and set it as the root element.

# Clone the DocumentFragment
df2 = docfragment.cloneNode( deep = 1)  

# Remove all the children of the root
for child in document.childNodes:
    document.removeChild( child )

# Add the cloned DocFrag to the root.
document.appendChild( df2 )

You could now call document.cloneNode(deep = 1) to get a new document
tree containing just that tree, or print document.toxml(), and repeat
the process with a new fragment.  A bit clumsy, but there seems no way
around it.

>Not the most elegant solution.  While I'm complaining, is there a good
>reason that HtmlWriter closes the file passed to it?  Because of that I

	Probably not; I've been annoyed at other functions which close
files on you, so the .close() should be removed.

-- 
A.M. Kuchling			http://starship.python.net/crew/amk/
To call such persons "humorists", a loose-fitting and ugly word, is to miss
the nature of their dilemma and the dilemma of their nature. The little wheels
of their invention are set in motion by the damp hand of melancholy.
    -- James Thurber, "Preface to A Life", in _The Thurber Carnival_