0

I am attempting to append elements to an existing .xml using ElementTree.

I have the desired attributes stored as a list of dictionaries:

myDict = [{"name": "dan",
           "age": "25",
           "subject":"maths"},
          {"name": "susan",
           "age": "27",
           "subject":"english"},
          {"name": "leo",
           "age": "24",
           "subject":"psychology"}]

And I use the following code for the append:

import xml.etree.ElementTree as ET
tree = ET.parse('<path to existing .xml')
root = tree.getroot()

for x,y in enumerate(myDict):
    root.append(ET.Element("student", attrib=myDict[x]))

tree.write('<path to .xml>')

This works mostly fine except that all elements are appended as a single line. I'd like to make each element append to be on a new line:

# Not this:
<student name='dan' age='25' subject='maths' /><student name='susan' age='27' subject='english' /><student name='leo' age='24' subject='psychology' />

# But this:
<student name='dan' age='25' subject='maths' />
<student name='susan' age='27' subject='english' />
<student name='leo' age='24' subject='psychology' />

I have attempted use lxml and pass the pretty_print=True argument within the tree.write call but it had no effect.

I'm sure I'm missing something simple here, so your help is appreciated!

r0bt
  • 383
  • 3
  • 12
  • [This](https://stackoverflow.com/questions/40085606/appending-multiple-elements-with-etree-how-to-write-each-element-on-new-line) question was about the same problem. – Gandhi Nov 22 '22 at 09:20
  • So according to [this](https://docs.python.org/2.7/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tail), I add `tail="\n"` when assigning attributes? `root.append(ET.Element("student", attrib=myDict[x], tail='\n'))`. I must be mistaken, doesn't seem to work. – r0bt Nov 22 '22 at 09:50
  • NVM. Sorted it. Will add my changes as an answer for clarity. Thanks for the pointer @Thicc_Gandhi – r0bt Nov 22 '22 at 10:00
  • Did you try `indent()`? https://stackoverflow.com/a/68618047/407651 – mzjn Nov 22 '22 at 10:01

1 Answers1

1

With pointers from here (Thanks @Thicc_Gandhi), I solved it by amending the iteration to:

for x,y in enumerate(MyDict):
    elem = ET.Element("student",attrib=myDict[x])
    elem.tail = "\n"
    root.append(elem)
r0bt
  • 383
  • 3
  • 12