all Python 3xml.etree.ElementTreefunction
xml.etree.ElementTree.SubElement()
tree and elements
Creates an element and appends it as the last child of a parent in one step. The main way to build an XML tree from scratch.
Syntax
child = ET.SubElement(parent, tag, attrib={}, **extra)
Unlike Element(), SubElement() needs no separate append(). Attribute values must be strings: a number in attrib makes serialization fail with TypeError, so write str(n). An attribute named like a keyword (class) goes in the attrib dict, not as class_=. Text is set by assigning .text afterwards; there is no text parameter. Since 3.8 attributes are written in insertion order, not alphabetically.
Examples
import xml.etree.ElementTree as ET
root = ET.Element('menu')
item = ET.SubElement(root, 'item', {'class': 'hot'}, price='5')
item.text = 'Чай'
print(ET.tostring(root, encoding='unicode'))
# → <menu><item class="hot" price="5">Чай</item></menu>
import xml.etree.ElementTree as ET
root = ET.Element('a')
ET.SubElement(root, 'b', n=5)
try:
ET.tostring(root)
except TypeError as e:
print(type(e).__name__) # → TypeError — нужно n='5'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy