8
votes

I'm using xml.etree.ElementTree to parse xml file. I'm parsing xml file in the following way:

import xml.etree.ElementTree as ET
tree = ET.parse(options.xmlfile)
root = tree.getroot()

This is my xml file:

<rootElement>
    <member>
        <member_id>439854395435</member_id>
    </member>
</rootElement>

Then I'm saving it:

tree.write(options.outcsvfile)

How can I make a copy of my tree to produce something like this:

<rootElement>
    <member>
        <member_id>439854395435</member_id>
    </member>
    <member>
        <member_id>439854395435</member_id>
    </member>
</rootElement>
1

1 Answers

11
votes

You can create a copy of the member element and append it. Example:

import xml.etree.ElementTree as ET
import copy

tree = ET.parse("test.xml")
root = tree.getroot() 

# Find element to copy 
member1 = tree.find("member")

# Create a copy
member2 = copy.deepcopy(member1)

# Append the copy 
root.append(member2)

print ET.tostring(root)

Output:

<rootElement>
    <member>
        <member_id>439854395435</member_id>
    </member>
<member>
        <member_id>439854395435</member_id>
    </member>
</rootElement>