0

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>
pklein
  • 3
  • 4
  • but this is only a formatting issue, or am I wrong? – Klops Apr 04 '23 at 11:20
  • It looks like you need to use the `indent` function: https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.indent – mzjn Apr 04 '23 at 11:21
  • See this answer for how to pretty print your xml https://stackoverflow.com/a/28814053/9659620 – Klops Apr 04 '23 at 11:28
  • Thanks for your help @Klops @mzjn, indeed that was `indent` I needed. I thought I have a problem with the encoding or the way I was writing my output file. – pklein Apr 04 '23 at 11:57

0 Answers0