PyDocs

Nav

Structured Markup Processing Tools

XMLParser

  • XMLParser(*, target=None, encoding=None)
This class is the low-level building block of the module. It uses xml.parsers.expat for efficient, event-based parsing of XML. It can be fed XML data incrementally with the feed() method, and parsing events are translated to a push API - by invoking callbacks on the target object. If target is omitted, the standard TreeBuilder is used. If encoding [1] is given, the value overrides the encoding specified in the XML file.
Changed in 3.8
  • 3.8: Parameters are now keyword-only. The html argument is no longer supported.
Members of XMLParser

c

close
Finishes feeding data to the parser.

f

feed
Feeds data to the parser.
flush
Triggers parsing of any previously fed unparsed data, which can be used to ensure more immediate feedback, in particular with Expat >=2.6.0.
1 Example
>>> from xml.etree.ElementTree import XMLParser
>>> class MaxDepth:                     # The target object of the parser
...     maxDepth = 0
...     depth = 0
...     def start(self, tag, attrib):   # Called for each opening tag.
...         self.depth += 1
...         if self.depth > self.maxDepth:
...             self.maxDepth = self.depth
...     def end(self, tag):             # Called for each closing tag.
...         self.depth -= 1
...     def data(self, data):
...         pass            # We do not need to do anything with data.
...     def close(self):    # Called when all data has been parsed.
...         return self.maxDepth
...
>>> target = MaxDepth()
>>> parser = XMLParser(target=target)
>>> exampleXml = """
... <a>
...   <b>
...   </b>
...   <b>
...     <c>
...       <d>
...       </d>
...     </c>
...   </b>
... </a>"""
>>> parser.feed(exampleXml)
>>> parser.close()
4
from the Python docs
See Also
No see-alsos for xml.etree.ElementTree/XMLParser
0 Notes
No notes for XMLParser