Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a copy of xml tree in python using ElementTree?

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>
like image 489
user1209304 Avatar asked Aug 11 '16 21:08

user1209304


People also ask

How do you access XML elements in Python?

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().

How do I change the root element in XML in Python?

_setroot(element): For replacing the root of a tree we can use this _setroot object. So it will replace the current tree with the new element that we have given, and discard the existing content of that tree. getroot(): The getroot() will return the root element of the tree.


1 Answers

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>
like image 174
mzjn Avatar answered Oct 04 '22 03:10

mzjn