Fedor March
Fedor March

Reputation: 87

how to xml add a new element to a new line

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?

Upvotes: 1

Views: 668

Answers (2)

Parolla
Parolla

Reputation: 407

Add

ET.indent(tree, '  ')

line before

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

Note: Feature available from Python 3.9

Upvotes: 1

Fedor March
Fedor March

Reputation: 87

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/>

Upvotes: 1

Related Questions