Skip to content
Advertisement

Adding n after every element in an XML python

I’m making an automation that takes an existing XML file, changes one of the values and overwrites the file.

My main problem is that its important for me to keep the formatting of the original file and i can’t manage to do that, the new data has no line breaks and its all just a long line.

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

My code is:

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

How can i add an n after each element? Thanks!

Advertisement

Answer

As far as I understand, the below is what you are looking for.

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 below

<StationConfig StationId="123" SportType="null" StationType="null" UseMetricSystem="US" LocalTempStorageDrive="C:" LocalStorageDrive="C:">
    <ClubManagementEnable ClubManagementStaticHours="">false</ClubManagementEnable>
</StationConfig>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement