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

前端 未结 1 530
再見小時候
再見小時候 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 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 element within for loop instead :

    for i, item in enumerate(xml):
        sub = etree.fromstring('')
        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():
    
      
        
      
      
        
      
    
    

    0 讨论(0)
提交回复
热议问题