How do I set attributes for an XML element with Python?

Venkatesh picture Venkatesh · Sep 14, 2013 · Viewed 33.5k times · Source

I am using ElementTree to build an XML file.

When I try to set an element's attribute with ET.SubElement().__setattr__(), I get the error AttributeError: __setattr__.

import xml.etree.cElementTree as ET
summary = open(Summary.xml, 'w')
root = ET.Element('Summary')
ET.SubElement(root, 'TextSummary')
ET.SubElement(root,'TextSummary').__setattr__('Status','Completed') # Error occurs here
tree = ET.ElementTree(root) 
tree.write(summary)
summary.close()

After code execution, my XML should resemble the following:

<Summary>
    <TextSummary Status = 'Completed'/>
</Summary>

How do I add attributes to an XML element with Python using xml.etree.cElementTree?

Answer

Thomas Orozco picture Thomas Orozco · Sep 14, 2013

You should be doing:

ET.SubElement(root,'TextSummary').set('Status','Completed')

The Etree documentation shows usage.