在另一棵树下插入一棵树(lxml)

时间:2015-12-03 14:13:29

标签: python xml lxml

我需要将一个XML树的全部内容插入到另一个树中(在具有特定标记的元素下)。我使用iter()方法迭代要修改的树的元素。问题是,第一棵树由于某种原因只插入一次。

有谁能告诉我我做错了什么?

from lxml import etree

# Creating the first tree
root1 = etree.Element('root', name = 'Root number one')
tree1 = etree.ElementTree(root1)

for n in range(1, 5):
    new_element = etree.SubElement(root1, 'element' + str(n))
    new_child = etree.Element('child')
    new_child.text = 'Test' + str(n)
    new_element.insert(0, new_child)

# Creating the second tree
root2 = etree.Element('root', name = 'Root number two')
tree2 = etree.ElementTree(root2)

for n in range(1, 3):
    new_element = etree.SubElement(root2, 'element')
    new_child = etree.Element('child')
    new_child.text = 'Test' + str(n)
    new_element.insert(0, new_child)

# Printing the trees to files to see what they look like
outFile1 = open('file1.xml', 'w')
print(etree.tostring(tree1, encoding='unicode', pretty_print=True), file=outFile1)

outFile2 = open('file2.xml', 'w')
print(etree.tostring(tree2, encoding='unicode', pretty_print=True), file=outFile2)

# Here I'm using the iter() method to iterate over the elements of tree2
# Under each element tagged as "element" I need to insert the whole contents
# of tree1
for element in tree2.iter():
    if element.tag == 'element':
        new_child = tree1.getroot()
        element.insert(0, new_child)

outFile3 = open('file3.xml', 'w')
print(etree.tostring(tree2, encoding='unicode', pretty_print=True), file=outFile3)

1 个答案:

答案 0 :(得分:2)

Quoth the lxml tutorial

  

如果要元素复制到lxml.etree中的其他位置,请考虑使用Python标准库中的copy模块创建独立的深层副本。

所以,在你的例子中,

for element in tree2.iter():
    if element.tag == 'element':
        new_child = copy.deepcopy(tree1.getroot())
        element.insert(0, new_child)