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

Вихідний код: 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.

Примітка

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

Змінено в версії 3.7.1: Синтаксичний аналізатор SAX більше не обробляє загальні зовнішні сутності за замовчуванням, щоб підвищити рівень безпеки за замовчуванням. Щоб увімкнути обробку зовнішніх об’єктів, передайте настроюваний екземпляр аналізатора в:

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)

Приклад:

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.

Оскільки документ розглядається як «плоский» потік подій, «дерево» документа обходиться неявно, і потрібні елементи знаходять незалежно від їх глибини в дереві. Іншими словами, не потрібно розглядати ієрархічні проблеми, такі як рекурсивний пошук вузлів документа, хоча, якби контекст елементів був важливим, потрібно було б підтримувати певний контекстно-пов’язаний стан (тобто запам’ятовувати, де ви знаходитесь у документі) у будь-який момент) або використати метод DOMEventStream.expandNode() і перейти до обробки, пов’язаної з 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)

Повертає DOMEventStream із заданого введення. stream_or_string може бути ім’ям файлу або файлоподібним об’єктом. parser, якщо задано, має бути об’єктом XMLReader. Ця функція змінить обробник документів аналізатора та активує підтримку простору імен; іншу конфігурацію синтаксичного аналізатора (наприклад, налаштування розв’язувача сутностей) потрібно було виконати заздалегідь.

Якщо у вас є XML у рядку, ви можете використовувати замість нього функцію 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

Значення за замовчуванням для параметра bufsizeparse().

Значення цієї змінної можна змінити перед викликом parse(), і нове значення набуде чинності.

Об’єкти 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.

Змінено в версії 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)

Розгортає всі дочірні елементи node у node. Приклад:

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.