Reputation: 43
I want to create an element tree like this in Python:
<parent>
<child/>
<child/>
<child/>
</parent>
I want to use it as an empty template that I can work on later. However, I cannot insert or append multiple <child>
element to the <parent>
element, though etree.SubElement
works. To be more specific:
This produces <parent><child/></parent>
, i.e., only one <child>
got inserted:
root = etree.Element('root')
child = etree.Element('child')
for i in range(3):
root.insert(0,child)
This does not work either and produce the same result as above:
root = etree.Element('root')
child = etree.Element('child')
for i in range(3):
root.append(child)
This works:
root = etree.Element('root')
for i in range(3):
etree.SubElement('child')
I don't understand why I cannot insert or append an element for multiple times.
Upvotes: 1
Views: 13295
Reputation: 176
I guess you need to create new element objects to append them to the root, otherwise it is the same element that you append twice, which has no effect :
root = etree.Element('root')
for i in range(3):
child = etree.Element('child')
root.append(child)
Hope this helps.
Upvotes: 3