在 XML python 中的每个元素后添加 \n

Adding \n after every element in an XML python

我正在制作一个自动化程序,它采用现有的 XML 文件,更改其中一个值并覆盖该文件。

我的主要问题是,保持原始文件的格式对我来说很重要,但我无法做到这一点,新数据没有换行符,只有很长的一行。

<StationConfig StationId="8706" SportType="null" StationType="null" UseMetricSystem="US" LocalTempStorageDrive="C:\" LocalStorageDrive="C:\">
<ClubManagementEnable ClubManagementStaticHours="">false</ClubManagementEnable>
</StationConfig>

我的代码是:

parser = etree.XMLParser()
    read = etree.parse("C:\StationConfig.xml", parser=parser).getroot()
    read.set("StationId", "8706")
    tree = etree.ElementTree(read)
    tree.write("C:\devtree\Station.xml", pretty_print=True)

如何在每个元素后添加一个\n? 谢谢!

据我了解,以下是您要查找的内容。

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<StationConfig StationId="8706" SportType="null" StationType="null" UseMetricSystem="US" LocalTempStorageDrive="C:\" LocalStorageDrive="C:\">
   <ClubManagementEnable ClubManagementStaticHours="">false</ClubManagementEnable>
</StationConfig>'''


def _pretty_print(current, parent=None, index=-1, depth=0):
    for i, node in enumerate(current):
        _pretty_print(node, current, i, depth + 1)
    if parent is not None:
        if index == 0:
            parent.text = '\n' + ('\t' * depth)
        else:
            parent[index - 1].tail = '\n' + ('\t' * depth)
        if index == len(parent) - 1:
            current.tail = '\n' + ('\t' * (depth - 1))


root = ET.fromstring(xml)
# change something in the xml
root.attrib['StationId'] = '123'
# save it back to disk
_pretty_print(root)
tree = ET.ElementTree(root)
tree.write("out.xml")

out.xml低于

<StationConfig StationId="123" SportType="null" StationType="null" UseMetricSystem="US" LocalTempStorageDrive="C:" LocalStorageDrive="C:">
    <ClubManagementEnable ClubManagementStaticHours="">false</ClubManagementEnable>
</StationConfig>