循环中的lxml.etree._Element.append()无法正常工作 [英] lxml.etree._Element.append() from a loop not working as expected

查看:136
本文介绍了循环中的lxml.etree._Element.append()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在这段代码中append()似乎可以在循环内部工作,但是生成的xml仅显示最后一次迭代的修改,而remove()可以正常工作.这是一个过于简化的示例,我正在处理大量数据,并且需要将相同的子树附加到许多不同的父级.

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, while remove() works as expected. This is a overly simplified example, I'm working with big chunks of data, and need to append the same subtree to many different parents.

from lxml import etree

xml = etree.fromstring('<tree><fruit id="1"></fruit><fruit id="2"></fruit></tree>')
sub = etree.fromstring('<apple/>')

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

print('\nResulting tree after iterating through items with append():\n' +
    etree.tostring(xml, pretty_print=True).decode('ascii'))

for item in xml:
    xml.remove(item)

print('Resulting tree after iterating through items with remove():\n' +
    etree.tostring(xml, pretty_print=True).decode('ascii'))

当前输出:

Fruit 0 with sub appended: <fruit id="1"><apple/></fruit>
Fruit 1 with sub appended: <fruit id="2"><apple/></fruit>

Resulting tree after iterating through items with append():
<tree>
  <fruit id="1"/>
  <fruit id="2">
    <apple/>
  </fruit>
</tree>

Resulting tree after iterating through items with remove():
<tree/>

append() 遍历项目后,的预期输出:

Expected output from after iterating through items with append():

<tree>
  <fruit id="1"/>
    <apple/>
  </fruit>
  <fruit id="2">
    <apple/>
  </fruit>
</tree>

推荐答案

这是因为您仅创建了要附加的一个实例 .因此,基本上,您只是将一个实例从一个父对象移到了另一个,直到最后一个append(sub)执行.尝试在for循环内移动<apple/>元素的创建:

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()

输出:

Resulting tree after iterating through items with append():
<tree>
  <fruit id="1">
    <apple/>
  </fruit>
  <fruit id="2">
    <apple/>
  </fruit>
</tree>

这篇关于循环中的lxml.etree._Element.append()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆