minidom appendChild confusion

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Marco

    #1

    minidom appendChild confusion

    Hello!

    Can anyone explain why the following code does not work?
    (I'm using python2.4.)


    Cheers, Marco

    --

    # the following code does _not_ work.
    # intended: put child-nodes as children to another node

    from xml.dom.minidom import Document
    doc = Document()
    node1 = doc.createEleme nt('one')
    el1 = doc.createEleme nt('e1')
    el2 = doc.createEleme nt('e1')
    node1.appendChi ld(el1)
    node1.appendChi ld(el2)
    assert 2 == len(node1.child Nodes) # ok

    doc2 = Document()
    node2 = doc2.createElem ent('two')

    for el in node1.childNode s:
    node2.appendChi ld(el)

    assert 2 == len(node2.child Nodes), "node2 has an unexpected number of
    children"

  • Peter Otten

    #2
    Re: minidom appendChild confusion

    Marco wrote:
    [color=blue]
    > Can anyone explain why the following code does not work?
    > (I'm using python2.4.)[/color]
    [color=blue]
    > # the following code does _not_ work.
    > # intended: put child-nodes as children to another node
    >
    > from xml.dom.minidom import Document
    > doc = Document()
    > node1 = doc.createEleme nt('one')
    > el1 = doc.createEleme nt('e1')
    > el2 = doc.createEleme nt('e1')
    > node1.appendChi ld(el1)
    > node1.appendChi ld(el2)
    > assert 2 == len(node1.child Nodes) # ok
    >
    > doc2 = Document()
    > node2 = doc2.createElem ent('two')
    >
    > for el in node1.childNode s:
    > node2.appendChi ld(el)[/color]

    A node added to node2's children is implicitly removed from node1's
    children. So you are iterating over the node1.childNode s list while
    altering it, which typically results in skipping every other item:
    [color=blue][color=green][color=darkred]
    >>> a = list("abcde")
    >>> for i in a:[/color][/color][/color]
    .... a.remove(i)
    ....[color=blue][color=green][color=darkred]
    >>> a[/color][/color][/color]
    ['b', 'd']

    You can avoid that by making a copy of node1.childNode s:

    for el in list(node1.chil dNodes):
    node2.appendChi ld(el)

    [color=blue]
    > assert 2 == len(node2.child Nodes), "node2 has an unexpected number of
    > children"[/color]

    Peter

    Comment

    • Marco

      #3
      Re: minidom appendChild confusion

      That's it. Thank you very much!

      Marco

      Comment

      Working...