Add element with attribute to XML in Python

Viewed 140

I need my XML file to look like:

<house>
  <window>
     <door color="blue">
         <table size="32">
          (other things will be here in the middle)
         </table>
     </door>
  </window>
</house>

I already have the house and the windows. How can I add the doors and the tables? I'm using xml.etree.ElementTree and I've tried adding them as subelements, like this:

root = ET.parse(filename).getroot()
path = root.find('window')
new = ET.SubElement(path, "door", color="blue")

I've also tried adding it as an element like this:

new = ET.Element("window", dict(color="blue"))
path.append(new)

But this doesn't fulfill my goal, because they need to close at the end (</door>), and all I'm getting is <door color="blue"/>.

1 Answers

Since your username and my avatar match :) try these changes - use the short_empty_elements() argument:

new = ET.SubElement(path, "door", color="blue")
print(ET.tostring(root, short_empty_elements=False).decode())

Output:

<house>
  <window>
     <door color="blue">
         <table size="32">
          (other things will be here in the middle)
         </table>
     </door>
  <door color="blue"></door></window>
</house>
Related