You can specify SubElement
attributes at creation time using keyword arguments:
root = ET.Element('Summary') ET.SubElement(root, 'TextSummary', Status='Completed')
Alternatively, you can use .set
to add an attribute to an element after creation.
root = ET.Element('Summary') sub = ET.SubElement(root, 'TextSummary') sub.set('Status', 'Completed')
Python example:
import xml.etree.ElementTree as ET root = ET.Element('Summary') ET.SubElement(root, 'TextSummary', Status='Completed') print(ET.tostring(root).decode())
XML Output:
<Summary> <TextSummary Status = "Completed"/> </Summary>
Explanation:
Constructors for Element
and SubElement
include **extra
, which accepts attributes as keyword arguments.
xml.etree.ElementTree.Element(tag, attrib={}, **extra) xml.etree.ElementTree.SubElement(parent, tag, attrib={}, **extra)
This allows you to add an arbitrary number of attributes.
root = ET.Element('Summary', Date='2018/07/02', Timestamp='11:44am') # <Summary Date = "2018/07/02" Timestamp = "11:44am">
You can also use .set
to add attributes to a pre-existing item. However, this can only add one item at a time. ( Offered by Thomas Orozco ).
root = ET.Element('Summary') root.set('Date', '2018/07/02') root.set('Timestamp', '11:44am') # <Summary Date = "2018/07/02" Timestamp = "11:44am">