10

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()
gabesz
  • 133
  • 1
  • 1
  • 9
  • 2
    What have you tried so far? What library are you using? Please show what you've done so we can help resolve your issue. (If you haven't tried anything on your own yet, please do so and come back here if you have a specific issue. I'd recommend the [lxml](http://lxml.de) library for working with XML in Python) – Hayden Schiff Aug 12 '15 at 19:56
  • Well, I'm try to use the xml.etree.ElementTree library. Unfortunately it is not as simple as it appears, because there are lots of .. nodes. import xml.etree.ElementTree as ET file=open("6x6.xml", "r") site=ET.Element("b") for c in file: site.append(c) file.write("out.xml") file.close() – gabesz Aug 12 '15 at 20:08
  • 1
    Please post your code in your question so that it is easier to read. – Hayden Schiff Aug 12 '15 at 20:10

1 Answers1

17

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

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137