修改(添加子元素)到xml并用ElementTree保存

问题描述 投票:0回答:0

我知道 StackOverflow 上有不同的类似主题,但我无法找出我的示例中的问题。

我有一个模板 xml 文件。我想使用这个模板来添加新的子元素并保存一个新的(修改过的)xml 文件。

输入xml文件

输入的 xml 文件如下所示:

<?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>

所需的 xml 输出文件

我想通过添加新的子元素来创建一个新的 xml 文件 un

filePaths
。 所需的输出文件应如下所示:

<?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>

我试过的

到目前为止我写的代码是:

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")

我的试用得到什么

我得到这样的输出:

<MaxQuantParams>
   <filePaths>
      
   <string>file1.raw</string><string>file2.raw</string></filePaths>
</MaxQuantParams>
python xml elementtree
© www.soinside.com 2019 - 2024. All rights reserved.