"xml.dom.pulldom" --- Support for building partial DOM trees
************************************************************

**Source code:** Lib/xml/dom/pulldom.py

======================================================================

The "xml.dom.pulldom" module provides a "pull parser" which can also
be asked to produce DOM-accessible fragments of the document where
necessary. The basic concept involves pulling "events" from a stream
of incoming XML and processing them. In contrast to SAX which also
employs an event-driven processing model together with callbacks, the
user of a pull parser is responsible for explicitly pulling events
from the stream, looping over those events until either processing is
finished or an error condition occurs.

Nota:

  If you need to parse untrusted or unauthenticated data, see XML
  security.

Distinto en la versión 3.7.1: El analizador SAX ya no procesa
entidades externas generales de forma predeterminada para aumentar la
seguridad de forma predeterminada. Para habilitar el procesamiento de
entidades externas, pase una instancia de analizador personalizada
(*custom parser instance in::*)

   from xml.dom.pulldom import parse
   from xml.sax import make_parser
   from xml.sax.handler import feature_external_ges

   parser = make_parser()
   parser.setFeature(feature_external_ges, True)
   parse(filename, parser=parser)

Ejemplo:

   from xml.dom import pulldom

   doc = pulldom.parse('sales_items.xml')
   for event, node in doc:
       if event == pulldom.START_ELEMENT and node.tagName == 'item':
           if int(node.getAttribute('price')) > 50:
               doc.expandNode(node)
               print(node.toxml())

"event" is one of the following constants, and "node" is the node
which the event is about. The nodes implement the "xml.dom"
interfaces; they are created by the DOM implementation given to
"PullDOM", which is "xml.dom.minidom" by default.

xml.dom.pulldom.START_DOCUMENT
xml.dom.pulldom.END_DOCUMENT

   The start and the end of the document. *node* is the "Document".

xml.dom.pulldom.START_ELEMENT
xml.dom.pulldom.END_ELEMENT

   The start tag and the end tag of an element. *node* is the
   "Element".

xml.dom.pulldom.CHARACTERS

   Character data. *node* is the "Text" node.

xml.dom.pulldom.IGNORABLE_WHITESPACE

   White space in element content, as declared in the DTD. *node* is
   the "Text" node.

xml.dom.pulldom.COMMENT

   A comment. *node* is the "Comment" node.

xml.dom.pulldom.PROCESSING_INSTRUCTION

   A processing instruction. *node* is the "ProcessingInstruction"
   node.

Puesto que el documento se trata como una secuencia "flat" (plana) de
eventos, el documento "tree" (árbol) se atraviesa implícitamente y los
elementos deseados se encuentran independientemente de su profundidad
en el árbol. En otras palabras, no es necesario tener en cuenta
cuestiones jerárquicas como la búsqueda recursiva de los nodos de
documento, aunque si el contexto de los elementos fuera importante, es
necesario mantener algún estado relacionado con el contexto (es decir,
recordar dónde se encuentra en el documento en un momento dado) o
hacer uso del método "DOMEventStream.expandNode()" y cambiar al
procesamiento relacionado con DOM.

class xml.dom.pulldom.PullDOM(documentFactory=None)

   Subclass of "xml.sax.handler.ContentHandler" which turns SAX events
   into the events of the pull parser. The nodes are created, but they
   are not added to the tree, unless "expandNode()" is called.
   *documentFactory*, if given, is a DOM implementation used to create
   the document; by default the implementation of "xml.dom.minidom" is
   used.

class xml.dom.pulldom.SAX2DOM(documentFactory=None)

   Subclass of "PullDOM" which also adds every created node to the
   tree, so that the complete document is built.

xml.dom.pulldom.parse(stream_or_string, parser=None, bufsize=None)

   Retorna un "DOMEventStream" de la entrada dada. *stream_or_string*
   (secuencia o cadena) puede ser un nombre de archivo o un objeto
   similar a un archivo, *parser*, si se indica, debe ser un objeto
   "XMLReader". Esta función cambiará el controlador de documentos del
   analizador y activará el soporte de espacios de nombres; otra
   configuración del analizador (como establecer un solucionador de
   entidades) debe haberse realizado de antemano.

Si tiene XML en una cadena, puede usar en su lugar la función
"parseString()":

xml.dom.pulldom.parseString(string, parser=None)

   Return a "DOMEventStream" that represents the *string*. *string*
   must be a "str" instance; to parse bytes, pass a binary file object
   to "parse()".

xml.dom.pulldom.default_bufsize

   Valor predeterminado para el parámetro *bufsize* para "parse()".

   El valor de las variables puede ser cambiado antes de llamar a
   "parse()" y el nuevo valor tendrá efecto.


Objetos DOMEventStream
======================

class xml.dom.pulldom.DOMEventStream(stream, parser, bufsize)

   Produce the events for the data read from the file object *stream*
   by the "XMLReader" *parser*. The data is read by *bufsize* bytes,
   or characters for a text stream, at a time.

   Distinto en la versión 3.11: Support for "__getitem__()" method has
   been removed.

   getEvent()

      Return the next "(event, node)" tuple, or "None" at the end of
      the document. See above for the events and the corresponding
      nodes. The current node does not contain information about its
      children, unless "expandNode()" is called.

   expandNode(node)

      Expande todos los hijos de *node* en *node* (nodo en nodo).
      Ejemplo:

         from xml.dom import pulldom

         xml = '<html><title>Foo</title> <p>Some text <div>and more</div></p> </html>'
         doc = pulldom.parseString(xml)
         for event, node in doc:
             if event == pulldom.START_ELEMENT and node.tagName == 'p':
                 # Following statement only prints '<p/>'
                 print(node.toxml())
                 doc.expandNode(node)
                 # Following statement prints node with all its children '<p>Some text <div>and more</div></p>'
                 print(node.toxml())

   reset()

      Discard the events which are not read yet and prepare the object
      for parsing a new document.

   clear()

      Release the parser and the document. The stream is not closed,
      and the object can no longer be used.
