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()
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 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
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.
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:
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
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