1

Executing the code:

parser = ET.XMLParser(strip_cdata=False, )
tree = ET.parse(f'copy_{xml_file}', parser)
root[0].insert(0, ET.Element("type"))
root.write("test.xml", pretty_print=True)

And the element I added creates not on a new line but in front of another element, it turns out the form:

    <firstTeg>327</firstTeg>
    <secondTeg>1.0</secondTeg><type/>
    

I need to get this kind of:

    <firstTeg>327</firstTeg>
    <secondTeg>1.0</secondTeg>
    <type/>

How do I create a new tag on a new line?

  • For xml it does not matter – balderman Aug 02 '22 at 20:13
  • 1
    Did you try to add `ET.indent(tree, ' ')` before `write`? – Parolla Aug 02 '22 at 20:15
  • @balderman unfortunately, this matters to the person working further with this xml) – Fedor March Aug 02 '22 at 20:15
  • @Parolla Until you pointed it out, I didn't even know. It really works. Could you please write this below as an answer, I will answer it as a solution to my question, for future seekers – Fedor March Aug 02 '22 at 20:22
  • This is about "pretty-printing". There are many existing questions and answers about it already. For example https://stackoverflow.com/q/749796/407651 – mzjn Aug 02 '22 at 20:26
  • @mzjn You are right, but, for example, the key `pretty_print=True` in the `tree.write` method did not help me. `xml.dom.minidom' - it is necessary to additionally import and configure, I have also met `remove_blank_text = True` advised, but there is no token. And according to the method proposed above - just one added line solves this problem – Fedor March Aug 02 '22 at 20:32

2 Answers2

1
parser = ET.XMLParser(strip_cdata=False, )
tree = ET.parse(f'copy_{xml_file}', parser)
new_elem = ET.Element("type")
new_elem.tail ="\n    "
root[0].insert(0, new_elem)
root.write("test.xml", pretty_print=True)

output:

<firstTeg>327</firstTeg>
<secondTeg>1.0</secondTeg>
<type/>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 04 '22 at 15:54
1

Add

ET.indent(tree, '  ')

line before

root.write("test.xml", pretty_print=True)

Note: Feature available from Python 3.9

Parolla
  • 408
  • 2
  • 6
  • The question is about lxml. `indent()` was added in lxml 4.5: https://lxml.de/4.5/changes-4.5.0.html. – mzjn Aug 03 '22 at 06:10