-1

I am trying to get new line after the xml declaration due to a external software that rejects xml-file when not having the new line.

The XML-template (which works fine with the software):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Test_XML>
 <DocumentProperties>
   <Title>Setup</Title>
...

Parsing of template, editing and writing in new file with

from xml.dom import minidom
dat = minidom.parse('template.xml')
 
...
 
file = open("template_edited.xml", "w")
dat.writexml(file, indent='', addindent='', newl='', encoding='UTF-8', standalone='yes')
file.close()

The edited XML-file output is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Test_XML>
 <DocumentProperties>
  <Title>Setup</Title>
...

Edited version is rejected by software, as new line is missing.

I tried to solve issue by using toxml(); toprettyxml(); adding /n, adding empty newchild after declaration but nothing worked yet. Wanted to stay with xml methods and not starting to slice and join strings.

Do you have an idea to get the new line in the edited version or to prevent that the new line of the template gets lost in the process?

There is a similar question XmlDocument, preformatted xml: Add new line after XML declaration only, but I could not solve it with the answer.

mzjn
  • 48,958
  • 13
  • 128
  • 248
amicode
  • 1
  • 1

1 Answers1

0

Add the newline by opening, editing and rewriting your file:

file_1 = open('wrong_formated.xml', 'r')
Lines = file_1.readlines()
file_2 = open('new_formated.xml', 'w')

line_number = 0
for line in Lines:
    if line_number == 1:
        file_2.writelines("\n")
    file_2.writelines(line)
    line_number += 1

Sure not the best solution but does it.

Oivalf
  • 154
  • 7
  • This way a new line is added after the first line. But it should be between declaration and ''. Means I would have to cut the line after '?>'. – amicode Aug 26 '22 at 10:24