0

I am trying to add a subitem to an existing XML file. I can add the element but its added to an existing element line and not on a new line.

I have tried using the toprettyxml() function but this just doubles the line spacing

Here is XML being read

<MainItem config="mainItem">
    <DisplayName name="" />
    <SubItems>
        <SubItem path="path01" />
        <SubItem path="path02" />
        <SubItem path="path03" />
    </SubItems>
</MainItem>

My current code

from xml.dom.minidom import *

dom = parse(r"path/myfile")

element = dom.createElement("SubItem")
element.appendChild(dom.createTextNode("NewPath03"))

cd = dom.getElementsByTagName("SubItem")[2]
cd.parentNode.insertBefore(element, cd)

Here is result

<MainItem config="mainItem">
    <DisplayName name=""/>
    <SubItems>
        <SubItem path="path01"/>
        <SubItem path="path02"/>
        <SubItem>NewPath03</SubItem><SubItem path="path03"/>
    </SubItems>
</MainItem>

The expected result

<MainItem config="mainItem">
    <DisplayName name="" />
    <SubItems>
        <SubItem path="path01" />
        <SubItem path="path02" />
        <SubItem path="path03" />
        <SubItem path="path04" />
    </SubItems>
</MainItem>
Dijkgraaf
  • 11,049
  • 17
  • 42
  • 54
Darren
  • 3
  • 1
  • 1
    This might not answer your question but to get closer to the output you want replace `cd.parentNode.insertBefore(element)` with `cd.parentNode.appendChild(element)` and `element.appendChild(dom.createTextNode("NewPath03"))` with `element.setAttribute('path', 'path04')` – kkawabat Aug 15 '19 at 21:42

1 Answers1

1

Inspired by the comment from kkawabat and the pretty-printing recipe in this answer, I came up with the following:

from xml.dom.minidom import parse

dom = parse(r"/path/myfile")

element = dom.createElement("SubItem")
element.setAttribute('path', 'path04')

cd = dom.getElementsByTagName("SubItem")[2]
cd.parentNode.appendChild(element) 

def pretty_print(dom):
    return '\n'.join([line for line in dom.toprettyxml(indent=' '*4).split('\n') if line.strip()])

print(pretty_print(dom))

Output:

<?xml version="1.0" ?>
<MainItem config="mainItem">
    <DisplayName name=""/>
    <SubItems>
        <SubItem path="path01"/>
        <SubItem path="path02"/>
        <SubItem path="path03"/>
        <SubItem path="path04"/>
    </SubItems>
</MainItem>
mzjn
  • 48,958
  • 13
  • 128
  • 248