【问题标题】:Adding \n after every element in an XML python在 XML python 中的每个元素之后添加 \n
【发布时间】:2021-10-19 07:16:43
【问题描述】:

我正在做一个自动化,它采用现有的 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 ? 谢谢!

【问题讨论】:

标签: python xml pretty-print


【解决方案1】:

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

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>

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2017-08-30
    • 1970-01-01
    相关资源
    最近更新 更多