【问题标题】:Insert a tree under another tree (lxml)在另一棵树下插入一棵树 (lxml)
【发布时间】:2015-12-03 14:13:28
【问题描述】:

我需要将一棵 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)

【问题讨论】:

  • 下次请创建一个最小示例。

标签: python xml lxml


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    相关资源
    最近更新 更多