lxml.etree._Element.append() from a loop not working as expected

前端 未结 1 527
再見小時候
再見小時候 2021-01-21 01:49

I would like to know why in this code append() seems to work from inside the loop, but the resulting xml displays the modification from only the last iteration, whi

相关标签:
1条回答
  • 2021-01-21 02:26

    That's because you only created one instance of <apple/> to be appended. So basically you just moved that one instance from one parent to another until the last append(sub) executed. Try to move creation of the <apple/> element within for loop instead :

    for i, item in enumerate(xml):
        sub = etree.fromstring('<apple/>')
        item.append(sub)
        print('Fruit {} with sub appended: {}'.format(
            i, etree.tostring(item).decode('ascii')))
    print()
    

    output :

    Resulting tree after iterating through items with append():
    <tree>
      <fruit id="1">
        <apple/>
      </fruit>
      <fruit id="2">
        <apple/>
      </fruit>
    </tree>
    
    0 讨论(0)
提交回复
热议问题