python xml dom help please

Andrew Clover and-google at doxdesk.com
Thu Nov 27 01:42:35 CET 2003


John J. Lee <jjl at pobox.com> wrote:

> Why not just for node in list(nodeList)?

You're right! I never trusted list() to make a copy if it was already a
native list (as it is sometimes in eg. minidom) but, bothering to check the
docs, it is guaranteed to after all. Hurrah.

spam.meplease at ntlworld.com (deglog) wrote:

> def appendToDescendant(node):
>   walker.previousSibling()
>   while 1:
>     if walker.currentNode.hasChildNodes():
>       next = walker.nextNode()
>     else: break
>   walker.currentNode.appendChild(node)

Are you sure this is doing what you want? A TreeWalker's nextNode() method
goes to an node's next matching sibling, not into its children. To go into
the matching children you'd use TreeWalker.firstChild().

The function as written above appends the argument node to the first sibling
to have no child nodes, starting from the TreeWalker's current node or its
previous sibling if there is one.

I'm not wholly sure I understand the problem you're trying to solve. If you
just want to nest sibling elements as first children, you could do it without
Traversal or recursion, for example:

  def nestChildrenIntoFirstElements(parent):
    elements= [c for c in parent.childNodes if c.nodeType==c.ELEMENT_NODE]
    if len(elements)>=2:
      insertionPoint= elements[0]
      for element in elements[1:]:
        insertionPoint.appendChild(element)
        insertionPoint= element

(Untested but no reason it shouldn't work.)

> Strangely, the line checking "Game" is needed, because this firstnode
> is its own previous sibling - how can this be right?

4DOM is fooling you. It has inserted a <!DOCTYPE> declaration automatically
for you. (It probably shouldn't do that.) So the previous sibling of the
documentElement is the doctype; of course the doctype has the same nodeName
as the documentElement, so the debugging output is misleading.

-- 
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/




More information about the Python-list mailing list