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
?
You should be doing:
ET.SubElement(root,'TextSummary').set('Status','Completed')