0

I wanted to add Element with Subelements to my xml file using Python. But after changing file the Element and Subelement looks like a line, not like a xml-tree.

I do this:

tree = ET.parse('existing_file.xml')
root = tree.getroot()
new_object = ET.SubElement(root, 'object')
name = ET.SubElement(new_object, 'name')
name.text = 'car'
color = ET.SubElement(new_object, 'color')
color.text = 'Red'
new_tree = ET.ElementTree(root)
new_tree.write('new_file.xml')

But after this I've got file without structure like this:

<object><name>car</name><color>red</color></object>

But i need this:

<object>
     <name>car</name>
     <color>red</color>
</object>

what do I do wrong?

2
  • 1
    Use indent(). See stackoverflow.com/a/39482716/407651 Commented Apr 17, 2024 at 14:33
  • 1
    Nothing wrong with that. Both are equally valid. It's just not indented. Commented Apr 17, 2024 at 14:34

1 Answer 1

0

using

new_tree = ET.ElementTree(root)
ET.indent(new_tree)
new_tree.write('new_file.xml', xml_declaration=True, short_empty_elements=True)

or using xml.dom.minidom.parseString

new_object = ET.SubElement(root, 'object')
name = ET.SubElement(new_object, 'name')
name.text = 'car'
color = ET.SubElement(new_object, 'color')
color.text = 'Red'

# Convert the ElementTree to a string with indentation
xml_string = ET.tostring(root, encoding='unicode')

# Use minidom to format the XML string
dom = xml.dom.minidom.parseString(xml_string)
formatted_xml = dom.toprettyxml()

# Write the formatted XML to a new file
with open('new_file.xml', 'w') as f:
    f.write(formatted_xml)

<?xml version="1.0" ?>
<object>
    <name>car</name>
    <color>red</color>
    <object>
        <name>car</name>
        <color>Red</color>
    </object>
</object>
Sign up to request clarification or add additional context in comments.

1 Comment

I just saw that there are a lot of ways to format XML documents in this link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.