Python Glossary Русский

all Python 3xml.etree.ElementTreeterm

xml.etree.ElementTree.XMLParser

parsing

The low-level expat-based parser: it takes data through feed() and calls methods of a target object (start, end, data, close).

Syntax

parser = ET.XMLParser(*, target=None, encoding=None)
parser.feed(data)
result = parser.close()

Without a target it builds a tree via TreeBuilder and close() returns the root; with your own target close() returns whatever target.close() returns, so you can compute something from XML without building a tree at all. Since 3.8 its parameters are keyword-only: XMLParser(t) raises TypeError, write target=t. The default TreeBuilder drops comments and processing instructions. There is no protection from entity bombs, so use defusedxml for foreign XML. The old XMLTreeBuilder alias and html= are gone.

Examples

import xml.etree.ElementTree as ET
class Count:
    def __init__(self):
        self.n = 0
    def start(self, tag, attrib):
        self.n += 1
    def end(self, tag):
        pass
    def close(self):
        return self.n
p = ET.XMLParser(target=Count())
p.feed('<a><b/>')
p.feed('<b/></a>')
print(p.close())  # → 3

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy