Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I duplicate an xml element using Python?

Tags:

python

xml

I have an XML file that looks like this:

 <a>
   <b>
    <c>World</c>
   </b>
 </a>

and should look like this:

 <a>
  <b>
   <c>World</c>
   <c>World</c>
  </b>
 </a> 

My code is the following:

import xml.etree.ElementTree as ET

file=open("6x6.xml", "r")
site=file.ET.Element("b")
for c in file:
  site.append(c)
file.write("out.xml")
file.close()
like image 736
gabesz Avatar asked Aug 12 '15 19:08

gabesz


People also ask

How to parse an XML file in Python?

Using et.parse () function we parse the XML file into object ‘tree’ (Replace the file path with the path to your XML file). The parsing of our file will start at the root of the tree.

How to parse and iterate through an XML file?

Using et.parse () function we parse the XML file into object ‘tree’ (Replace the file path with the path to your XML file). The parsing of our file will start at the root of the tree. Using the .getroot () function, we get the root of the parsed tree. We can now use the root to iterate through our file. 3. Creating lists for record values

How to parse an XML file into Dom?

DOM applications often start by parsing XML into DOM. in xml.dom.minidom, this can be achieved in the following ways: The first method is to make use of the parse () function by supplying the XML file to be parsed as a parameter. For example: Once you execute this, you will be able to split the XML file and fetch the required data.

How to use Python XML parser using elementtree API?

Python ElementTree API is one of the easiest way to extract, parse and transform XML data. So let’s get started using python XML parser using ElementTree: First we are going to create a new XML file with an element and a sub-element. Once we run above program, a new file is created named “textXML.xml” in our current default working directory:


1 Answers

You can use copy.deepcopy() to achieve that, for example :

import xml.etree.ElementTree as ET
import copy

s = """<a>
   <b>
    <c>World</c>
   </b>
 </a>"""

file = ET.fromstring(s)
b = file.find("b")
for c in file.findall(".//c"):
    dupe = copy.deepcopy(c) #copy <c> node
    b.append(dupe) #insert the new node

print(ET.tostring(file))

output :

<a>
   <b>
    <c>World</c>
   <c>World</c>
   </b>
 </a>

Related question : etree Clone Node

like image 72
har07 Avatar answered Oct 01 '22 18:10

har07