I know there are different similar topics on StackOverflow but I cannot figure out the problem on my example.
I have a template xml file. I want to use this template to add new subelements and save a new (modified) xml file.
Input xml file
The input xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<MaxQuantParams xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<filePaths>
<!-- <string>/PATH/TO/RAW/FILE</string> -->
</filePaths>
</MaxQuantParams>
Desired xml output file
I would like to create a new xml file by adding new subElements un filePaths
.
The desired output file should look like this:
<?xml version="1.0" encoding="utf-8"?>
<MaxQuantParams xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<filePaths>
<string>file1.raw</string>
<string>file2.raw</string>
</filePaths>
</MaxQuantParams>
What I tried
The code I wrote so far is:
import xml.etree.ElementTree as ET
import copy
files = ["file1.raw", "file2.raw"]
# read xml template config file
config_template = ET.parse("input.xml")
# Create xml config file
config = copy.deepcopy(config_template)
root = config.getroot()
file_paths = root.find(".//filePaths")
for file in files:
child = ET.SubElement(file_paths, "string")
child.text = file
# save config file in output folder
tree = ET.ElementTree(root)
tree.write("out.xml", encoding="utf-8")
What I get for my trial
I get this kind of output:
<MaxQuantParams>
<filePaths>
<string>file1.raw</string><string>file2.raw</string></filePaths>
</MaxQuantParams>