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

Code source : 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.

Note

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

Modifié dans la version 3.7.1: l'analyseur SAX ne traite plus les entités externes générales par défaut pour augmenter la sécurité par défaut. Pour activer le traitement des entités externes, transmettez une instance d'analyseur personnalisée à :

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)

Exemple :

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.

Puisque le document est traité comme un flux « plat » d’événements, « l’arborescence » du document est implicitement parcourue et les éléments souhaités sont trouvés quelle que soit leur profondeur dans l’arborescence. En d'autres termes, il n'est pas nécessaire de prendre en compte les problèmes hiérarchiques tels que la recherche récursive des nœuds du document, même dans le cas où le contexte des éléments est important, et où il faudrait soit maintenir un état lié au contexte (c'est-à-dire se souvenir où l'on se trouve dans le document à un moment donné), soit utiliser la méthode DOMEventStream.expandNode() et passer au traitement lié du 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)

Renvoie un DOMEventStream à partir de l'entrée donnée. stream_or_string peut être soit un nom de fichier, soit un objet simili-fichier. parser, s'il est donné, doit être un objet XMLReader. Cette fonction modifie le gestionnaire de documents de l'analyseur et active la prise en charge des espaces de noms ; les autres configurations de l'analyseur (comme la définition d'un résolveur d'entité) doivent avoir été effectuées à l'avance.

Si vous avez du XML dans une chaîne, vous pouvez utiliser la fonction parseString() à la place :

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

Valeur par défaut du paramètre bufsize de parse().

La valeur de cette variable peut être modifiée avant d'appeler parse() et la nouvelle valeur prendra effet.

Objets 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.

Modifié dans la version 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)

Développe tous les enfants de node dans node. Par exemple :

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.