0

Basically I'm trying to add a new element and for it to be properly indented, but with this code I get unnecessary new lines between elements. What is causing it and how do I fix it? Thanks

Example:

from xml.dom import minidom
import xml.etree.ElementTree as ET

def example(name, category):
    tree = ET.parse("example1.xml")
    root = tree.getroot()

    for i in root:
        if i.tag == category:
            ET.SubElement(i, name).text = name

    xmlStr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="    ")
    with open("example1.xml", "w") as f:
        f.write(xmlStr)

example("test", 'FRUITS')

XML File:

<?xml version="1.0" ?>
<root>
    <FRUITS>
        <APPLE>apple</APPLE>
        <PEAR>pear</PEAR>
        <PLUM>plum</PLUM>
    </FRUITS>
    <VEGETABLES>
        <CARROT>carrot</CARROT>
        <POTATO>potato</POTATO>
    </VEGETABLES>
  • 1
    Instead of using minidom for pretty-printing, have you tried the `indent()` function in ElementTree? https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.indent – mzjn Nov 20 '22 at 07:49
  • I have python 3.11 but ElementTree doesn't have indent function, I can't seem to get it to work @mzjn – Solomon Baker Nov 20 '22 at 08:32
  • Does this help? https://stackoverflow.com/a/68618047/407651 or https://stackoverflow.com/a/63373633/407651 – mzjn Nov 20 '22 at 08:34
  • Already went through these, I can only think I didnt update python right, even tho it says version 3.11.0 – Solomon Baker Nov 20 '22 at 08:41

0 Answers0