all Python 3xml.etree.ElementTreeterm
xml.etree.ElementTree.TreeBuilder
parsing
Builds an Element tree from start/data/end calls — the default target of XMLParser; also useful for building a tree from a non-XML format.
Syntax
tb = ET.TreeBuilder(element_factory=None, *, comment_factory=None, pi_factory=None, insert_comments=False, insert_pis=False)
Comments and processing instructions are dropped by default; to keep them pass TreeBuilder(insert_comments=True, insert_pis=True) as the XMLParser target (3.8+), and only those inside the root are kept. Without a parser it builds a tree from any event source, as long as you keep start/end calls paired. data() may be called several times in a row; the pieces are joined into text or tail.
Examples
import xml.etree.ElementTree as ET
tb = ET.TreeBuilder()
tb.start('a', {'k': 'v'})
tb.data('hi')
tb.data('!')
tb.end('a')
print(ET.tostring(tb.close(), encoding='unicode')) # → <a k="v">hi!</a>
import xml.etree.ElementTree as ET
xml = '<a><!-- note --><b/></a>'
print(len(ET.fromstring(xml))) # → 1 — комментарий выброшен
p = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
p.feed(xml)
root = p.close()
print(len(root), root[0].tag is ET.Comment) # → 2 True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy