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>
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().
_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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With