xml.dom — The Document Object Model API

Вихідний код: Lib/xml/dom/__init__.py


Об’єктна модель документа, або «DOM», — це міжмовний API Консорціуму Всесвітньої павутини (W3C) для доступу та зміни документів XML. Реалізація DOM представляє XML-документ як структуру дерева або дозволяє коду клієнта створювати таку структуру з нуля. Потім він надає доступ до структури через набір об’єктів, які надають добре відомі інтерфейси.

DOM надзвичайно корисний для додатків із довільним доступом. SAX дозволяє переглядати лише один біт документа за раз. Якщо ви дивитеся на один елемент SAX, у вас немає доступу до іншого. Якщо ви дивитесь на текстовий вузол, ви не маєте доступу до вмісту елемента. Коли ви пишете програму SAX, вам потрібно відстежувати позицію вашої програми в документі десь у вашому власному коді. SAX не робить це за вас. Крім того, якщо вам потрібно дивитися вперед у документі XML, вам просто не пощастило.

Деякі програми просто неможливі в керованій подіями моделі без доступу до дерева. Звичайно, ви можете самостійно створити якесь дерево в подіях SAX, але DOM дозволяє вам уникнути написання цього коду. DOM — це стандартне представлення дерева для даних XML.

Об’єктна модель документа визначається W3C поетапно або «рівнями» за їхньою термінологією. Відображення Python API в основному базується на рекомендації DOM рівня 2.

Програми DOM зазвичай починаються з аналізу деякого XML у DOM. Як це досягається, взагалі не описано в DOM рівня 1, а рівень 2 передбачає лише обмежені покращення: існує клас об’єктів DOMImplementation, який надає доступ до методів створення Document, але не має можливості отримати доступ до зчитувача/аналізатора XML/конструктора документів у спосіб, незалежний від реалізації. Також немає чітко визначеного способу доступу до цих методів без наявного об’єкта Document. У Python кожна реалізація DOM надаватиме функцію getDOMImplementation(). DOM Level 3 додає специфікацію Load/Store, яка визначає інтерфейс для читача, але це ще не доступно в стандартній бібліотеці Python.

Якщо у вас є об’єкт документа DOM, ви можете отримати доступ до частин свого документа XML через його властивості та методи. Ці властивості визначені в специфікації DOM; ця частина довідкового посібника описує інтерпретацію специфікації в Python.

Специфікація, надана W3C, визначає DOM API для Java, ECMAScript і OMG IDL. Визначене тут відображення Python значною мірою базується на версії специфікації IDL, але сувора відповідність не потрібна (хоча реалізації можуть вільно підтримувати суворе відображення з IDL). Перегляньте розділ Відповідність для детального обговорення вимог до відображення.

Дивись також

Специфікація рівня 2 об’єктної моделі документа (DOM)

Рекомендація W3C, на якій базується API Python DOM.

Специфікація рівня 1 об’єктної моделі документа (DOM)

Рекомендація W3C щодо DOM, що підтримується xml.dom.minidom.

Специфікація відображення мови Python

Це визначає відображення з OMG IDL на Python.

Зміст модуля

The xml.dom contains the following functions:

xml.dom.registerDOMImplementation(name, factory)

Зареєструйте функцію factory з іменем name. Фабрична функція має повертати об’єкт, який реалізує інтерфейс DOMImplementation. Фабрична функція може щоразу повертати той самий об’єкт або новий для кожного виклику, залежно від конкретної реалізації (наприклад, якщо ця реалізація підтримує певні налаштування).

xml.dom.getDOMImplementation(name=None, features=())

Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If it is not None, imports the corresponding module and returns a DOMImplementation object if the import succeeds. If no name is given, and if the environment variable PYTHON_DOM is set, this variable is used to find the implementation. The only well-known name in the standard library is 'minidom', for xml.dom.minidom.

If name is not given, this examines the available implementations to find one with the required feature set. If no implementation can be found, raise an ImportError. The features list must be a sequence of (feature, version) pairs which are passed to the hasFeature() method on available DOMImplementation objects.

Також надано деякі зручні константи:

xml.dom.EMPTY_NAMESPACE

The value used to indicate that no namespace is associated with a node in the DOM. This is typically found as the namespaceURI of a node, or used as the namespaceURI parameter to a namespaces-specific method.

xml.dom.XML_NAMESPACE

URI простору імен, пов’язаний із зарезервованим префіксом xml, як визначено Просторами імен у XML (розділ 4).

xml.dom.XMLNS_NAMESPACE

URI простору імен для декларацій простору імен, як визначено Основною специфікацією рівня 2 об’єктної моделі документа (DOM) (розділ 1.1.8).

xml.dom.XHTML_NAMESPACE

URI простору імен XHTML, як визначено XHTML 1.0: розширювана мова розмітки гіпертексту (розділ 3.1.1).

In addition, xml.dom contains a base Node class and the DOM exception classes. The Node class provided by this module does not implement any of the methods or attributes defined by the DOM specification; concrete DOM implementations must provide those. The Node class provided as part of this module does provide the constants used for the nodeType attribute on concrete Node objects; they are located within the class rather than at the module level to conform with the DOM specifications.

Об’єкти в DOM

Основною документацією для DOM є специфікація DOM від W3C.

The names documented in this section are DOM interfaces. With the exception of Node and the exception classes, they are not provided by the xml.dom module itself, but by concrete DOM implementations, such as xml.dom.minidom.

Зауважте, що атрибути DOM також можна використовувати як вузли, а не як прості рядки. Однак це доводиться робити досить рідко, тому таке використання ще не задокументовано.

Інтерфейс

Розділ

призначення

DOMIimplementation

Об’єкти реалізації DOMI

Інтерфейс базової реалізації.

Node

Об’єкти Node

Базовий інтерфейс для більшості об’єктів у документі.

NodeList

Об’єкти NodeList

Інтерфейс для послідовності вузлів.

DocumentType

Об’єкти DocumentType

Інформація про декларації, необхідні для оформлення документа.

Document

Об’єкти документа

Об’єкт, який представляє весь документ.

Element

Об’єкти елементів

Вузли елементів в ієрархії документа.

Attr

Об’єкти Attr

Вузли значення атрибута на вузлах елемента.

Comment

Об’єкти коментарів

Відображення коментарів у вихідному документі.

Text

Текст і об’єкти CDATASection

Вузли, що містять текстовий вміст із документа.

ProcessingInstruction

Об’єкти інструкцій обробки

Представлення інструкцій обробки.

Додатковий розділ описує винятки, визначені для роботи з DOM у Python.

Об’єкти реалізації DOMI

Інтерфейс DOMImplementation надає програмам спосіб визначити доступність певних функцій у DOM, який вони використовують. Рівень 2 DOM також додав можливість створювати нові об’єкти Document і DocumentType за допомогою DOMImplementation.

DOMImplementation.hasFeature(feature, version)

Повертає True, якщо функцію, визначену парою рядків feature і version, реалізовано.

DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)

Повертає новий об’єкт Document (корінь DOM) з дочірнім об’єктом Element, який має вказані namespaceUri і qualifiedName. doctype має бути об’єктом DocumentType, створеним createDocumentType(), або None. В Python DOM API перші два аргументи також можуть бути None, щоб вказати, що дочірній елемент Element не створюватиметься.

DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)

Повертає новий об’єкт DocumentType, який інкапсулює задані рядки qualifiedName, publicId і systemId, що представляють інформацію, що міститься в декларації типу документа XML.

Об’єкти Node

Усі компоненти документа XML є підкласами Node.

Only nodes of the following types can have children, and only children of the listed types:

Document

at most one Element, at most one DocumentType, ProcessingInstruction and Comment

DocumentFragment and Element

Element, Text, CDATASection, ProcessingInstruction and Comment

Attr

Text

Nodes of other types cannot have children. Inserting a child of a not allowed type raises HierarchyRequestErr.

Node.nodeType

An integer representing the node type. Symbolic constants for the types are on the Node object. This is a read-only attribute.

Node.ELEMENT_NODE
Node.ATTRIBUTE_NODE
Node.TEXT_NODE
Node.CDATA_SECTION_NODE
Node.ENTITY_REFERENCE_NODE
Node.ENTITY_NODE
Node.PROCESSING_INSTRUCTION_NODE
Node.COMMENT_NODE
Node.DOCUMENT_NODE
Node.DOCUMENT_TYPE_NODE
Node.DOCUMENT_FRAGMENT_NODE
Node.NOTATION_NODE

Integer constants for the possible values of the nodeType attribute.

Node.parentNode

Батьківський елемент поточного вузла або None для вузла документа. Значенням завжди є об’єкт Node або None. Для вузлів Element це буде батьківський елемент, за винятком кореневого елемента, у якому випадку це буде об’єкт Document. Для вузлів Attr це завжди None. Це атрибут лише для читання.

Node.attributes

NamedNodeMap об’єктів атрибутів. Тільки елементи мають фактичні значення для цього; інші надають None для цього атрибута. Це атрибут лише для читання.

Node.previousSibling

Вузол, який безпосередньо передує цьому з тим же батьківським вузлом. Наприклад, елемент із кінцевим тегом, який стоїть безпосередньо перед початковим тегом елемента self. Звичайно, XML-документи складаються не лише з елементів, тому попередній брат може бути текстом, коментарем або чимось іншим. Якщо цей вузол є першим дочірнім вузлом батьківського, цей атрибут матиме значення None. Це атрибут лише для читання.

Node.nextSibling

Вузол, який слідує безпосередньо за цим із тим же батьківським вузлом. Дивіться також previousSibling. Якщо це останній дочірній елемент батьківського елемента, цей атрибут матиме значення None. Це атрибут лише для читання.

Node.childNodes

A NodeList of the children of this node. If the node has no children, the list is empty. This is a read-only attribute.

Node.firstChild

Перший дочірній елемент вузла, якщо він є, або None. Це атрибут лише для читання.

Node.lastChild

Останній дочірній елемент вузла, якщо він є, або None. Це атрибут лише для читання.

Node.localName

The part of the tagName following the colon if there is one, else the entire tagName. The value is a string.

Node.prefix

The part of the tagName preceding the colon if there is one, else the empty string. The value is a string, or None.

Node.namespaceURI

Простір імен, пов’язаний з іменем елемента. Це буде рядок або None. Це атрибут лише для читання.

Node.ownerDocument

The Document object to which this node belongs, or None for a document itself. This is a read-only attribute.

Node.isSupported(feature, version)

Return whether the DOM implementation supports a particular feature, as DOMImplementation.hasFeature() does.

Node.setUserData(key, data, handler)

Associate data with key on this node and return the data previously associated with key, or None. If data is None, the association is removed. handler is called when the node is cloned, imported, renamed or deleted; pass None if no notification is needed.

Node.getUserData(key)

Return the data associated with key on this node by setUserData(), or None.

Node.nodeName

The name of this node, depending on its type; see the table below. You can always get the information you would get here from another property such as the tagName property for elements or the name property for attributes. This is a read-only attribute.

Node.nodeValue

The value of this node, depending on its type; see the table below. The value is a string or None.

The values of nodeName and nodeValue for each node type are:

Node type

nodeName

nodeValue

Attr

name

value

CDATASection

'#cdata-section'

the content

Comment

'#comment'

the content

Document

'#document'

Жодного

DocumentFragment

'#document-fragment'

Жодного

DocumentType

name

Жодного

Element

tagName

Жодного

Entity

the name of the entity

Жодного

Notation

the name of the notation

Жодного

ProcessingInstruction

target

data

Text

'#text'

the content

Node.hasAttributes()

Повертає True, якщо вузол має будь-які атрибути.

Node.hasChildNodes()

Повертає True, якщо вузол має дочірні вузли.

Node.isSameNode(other)

Повертає True, якщо other посилається на той самий вузол, що й цей вузол. Це особливо корисно для реалізацій DOM, які використовують будь-яку архітектуру проксі (оскільки більше ніж один об’єкт може посилатися на один вузол).

Примітка

Це базується на запропонованому API рівня 3 DOM, який все ще перебуває на стадії «робочої чернетки», але цей конкретний інтерфейс не викликає суперечок. Зміни від W3C не обов’язково вплинуть на цей метод в інтерфейсі Python DOM (хоча будь-який новий API W3C для цього також підтримуватиметься).

Node.appendChild(newChild)

Додайте новий дочірній вузол до цього вузла в кінці списку дочірніх, повертаючи newChild. Якщо вузол уже був у дереві, його спочатку видаляють.

Node.insertBefore(newChild, refChild)

Insert a new child node before an existing child. It must be the case that refChild is a child of this node; if not, NotFoundErr is raised. newChild is returned. If refChild is None, it inserts newChild at the end of the children’s list.

Node.removeChild(oldChild)

Remove a child node. oldChild must be a child of this node; if not, NotFoundErr is raised. oldChild is returned on success. If oldChild will not be used further, its unlink() method should be called.

Node.replaceChild(newChild, oldChild)

Replace an existing node with a new node. It must be the case that oldChild is a child of this node; if not, NotFoundErr is raised.

Node.normalize()

Об’єднайте сусідні текстові вузли, щоб усі фрагменти тексту зберігалися як окремі екземпляри Text. Це спрощує обробку тексту з дерева DOM для багатьох програм.

Node.cloneNode(deep)

Клонуйте цей вузол. Установка deep також означає клонування всіх дочірніх вузлів. Це повертає клон.

Об’єкти NodeList

A NodeList represents a sequence of nodes. These objects are used in two ways in the DOM Core recommendation: an Element object provides one as its list of child nodes, and the getElementsByTagName() and getElementsByTagNameNS() methods of Node return objects with this interface to represent query results.

NodeList does not inherit from Node.

Рекомендація DOM рівня 2 визначає один метод і один атрибут для цих об’єктів:

NodeList.item(i)

Return the i’th item from the sequence, or None if i is out of range. Negative indices are not supported.

NodeList.length

Кількість вузлів у послідовності.

Крім того, для інтерфейсу DOM Python потрібна додаткова підтримка, щоб об’єкти NodeList могли використовуватися як послідовності Python. Усі реалізації NodeList повинні включати підтримку __len__() і __getitem__(); це дозволяє ітерацію по NodeList в for операторах і належну підтримку для len() вбудованої функції.

Якщо реалізація DOM підтримує модифікацію документа, реалізація NodeList також повинна підтримувати методи __setitem__() і __delitem__().

Об’єкти DocumentType

Information about the notations and entities declared by a document (including the external subset if the parser uses it and can provide the information) is available from a DocumentType object. The DocumentType for a document is available from the Document object’s doctype attribute; if there is no DOCTYPE declaration for the document, the document’s doctype attribute will be set to None instead of an instance of this interface.

DocumentType є спеціалізацією Node і додає такі атрибути:

DocumentType.publicId

The public identifier for the external subset of the document type definition, or None if the DOCTYPE declaration does not specify it.

DocumentType.systemId

The system identifier, a URI, for the external subset of the document type definition, or None if the DOCTYPE declaration does not specify it.

DocumentType.internalSubset

Рядок, що містить повну внутрішню частину документа. Це не включає дужки, які містять підмножину. Якщо документ не має внутрішньої підмножини, це має бути None.

DocumentType.name

Ім’я кореневого елемента, указане в декларації DOCTYPE, якщо воно є.

DocumentType.entities

This is a NamedNodeMap of Entity nodes giving the definitions of external entities. For entity names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). This may be None if the information is not provided by the parser, or if no entities are defined.

DocumentType.notations

This is a NamedNodeMap of Notation nodes giving the definitions of notations. For notation names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). This may be None if the information is not provided by the parser, or if no notations are defined.

Об’єкти документа

Document представляє весь XML-документ, включаючи його складові елементи, атрибути, інструкції з обробки, коментарі тощо. Пам’ятайте, що він успадковує властивості від Node.

Document.documentElement

Єдиний кореневий елемент документа.

Document.doctype

The DocumentType node of the document, or None. This is a read-only attribute.

Document.implementation

The DOMImplementation object which created this document. This is a read-only attribute.

Document.strictErrorChecking

Whether error checking is enforced.

Document.documentURI

The location of the document, or None if it is unknown.

Document.createDocumentFragment()

Create and return an empty DocumentFragment node.

Document.createCDATASection(data)

Create and return a CDATASection node containing data.

Document.importNode(importedNode, deep)

Return a copy of importedNode which belongs to this document. The original node is not removed from its document. If deep is true, the descendants of the node are copied too.

Document.createElement(tagName)

Create and return a new element node. The element is not inserted into the document when it is created. You need to explicitly insert it with one of the other methods such as insertBefore() or appendChild().

Document.createElementNS(namespaceURI, tagName)

Create and return a new element with a namespace. The tagName may have a prefix. The element is not inserted into the document when it is created. You need to explicitly insert it with one of the other methods such as insertBefore() or appendChild().

Document.createTextNode(data)

Створіть і поверніть текстовий вузол, що містить дані, передані як параметр. Як і в інших методах створення, цей не вставляє вузол у дерево.

Document.createComment(data)

Створіть і поверніть вузол коментаря, що містить дані, передані як параметр. Як і в інших методах створення, цей не вставляє вузол у дерево.

Document.createProcessingInstruction(target, data)

Створіть і поверніть вузол інструкцій обробки, що містить target і data, передані як параметри. Як і в інших методах створення, цей не вставляє вузол у дерево.

Document.createAttribute(name)

Create and return an attribute node. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance.

Document.createAttributeNS(namespaceURI, qualifiedName)

Create and return an attribute node with a namespace. The tagName may have a prefix. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance.

Document.getElementById(id)

Return the element with the given ID, or None. Only attributes declared as being of type ID in the DTD or by Element.setIdAttribute() are searched.

Document.getElementsByTagName(tagName)

Пошук усіх нащадків (прямих дітей, дітей дітей тощо) з певним ім’ям типу елемента.

Document.getElementsByTagNameNS(namespaceURI, localName)

Пошук усіх нащадків (прямих дітей, дітей дітей тощо) з певним URI простору імен і локальним іменем. Локальна назва - це частина простору імен після префікса.

Document.renameNode(n, namespaceURI, name)

Rename the element or attribute node n and return it. namespaceURI is the new namespace URI, or EMPTY_NAMESPACE if the node does not belong to a namespace. name is the new qualified name.

Raise WrongDocumentErr if n was created by another document, and NotSupportedErr if it is neither an element nor an attribute.

Об’єкти елементів

Element є підкласом Node, тому успадковує всі атрибути цього класу.

Element.tagName

Назва типу елемента. У документі, що використовує простір імен, у ньому можуть бути двокрапки. Значенням є рядок.

Element.setIdAttribute(name)

Declare that the attribute name is of type ID, so that the element is found by Document.getElementById(). Raise NotFoundErr if the element has no such attribute.

Element.setIdAttributeNS(namespaceURI, localName)

The same as setIdAttribute(), but for an attribute specified by its namespace URI and local name.

Element.setIdAttributeNode(idAttr)

The same as setIdAttribute(), but for an already retrieved attribute node.

Element.getElementsByTagName(tagName)

Те саме, що еквівалентний метод у класі Document.

Element.getElementsByTagNameNS(namespaceURI, localName)

Те саме, що еквівалентний метод у класі Document.

Element.hasAttribute(name)

Повертає True, якщо елемент має атрибут із назвою name.

Element.hasAttributeNS(namespaceURI, localName)

Повертає True, якщо елемент має атрибут, названий namespaceURI і localName.

Element.getAttribute(name)

Повертає значення атрибута з іменем name у вигляді рядка. Якщо такий атрибут не існує, повертається порожній рядок, як якщо б атрибут не мав значення.

Element.getAttributeNode(attrname)

Повертає вузол Attr для атрибута, названого attrname.

Element.getAttributeNS(namespaceURI, localName)

Повертає значення атрибута з назвою namespaceURI і localName як рядок. Якщо такий атрибут не існує, повертається порожній рядок, як якщо б атрибут не мав значення.

Element.getAttributeNodeNS(namespaceURI, localName)

Повертає значення атрибута як вузол із заданим namespaceURI і localName.

Element.removeAttribute(name)

Remove an attribute by name.

Element.removeAttributeNode(oldAttr)

Видаліть і поверніть oldAttr зі списку атрибутів, якщо він є. Якщо oldAttr відсутній, виникає помилка NotFoundErr.

Element.removeAttributeNS(namespaceURI, localName)

Remove an attribute by name. Note that it uses a localName, not a qname.

Element.setAttribute(name, value)

Установіть значення атрибута з рядка.

Element.setAttributeNode(newAttr)

Add a new attribute node to the element, replacing an existing attribute if necessary if the name attribute matches. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use, InuseAttributeErr will be raised.

Element.setAttributeNodeNS(newAttr)

Add a new attribute node to the element, replacing an existing attribute if necessary if the namespaceURI and localName attributes match. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use, InuseAttributeErr will be raised.

Element.setAttributeNS(namespaceURI, qname, value)

Установіть значення атрибута з рядка, заданого namespaceURI і qname. Зауважте, що qname — це повна назва атрибута. Це відрізняється від вищезазначеного.

Об’єкти Attr

Attr успадковує Node, тому успадковує всі його атрибути.

Attribute nodes are not part of the document tree. They are contained in the attributes map of an element, not in its children, and their parentNode, previousSibling and nextSibling are always None.

Attr.name

Назва атрибута. У документі, що використовує простір імен, він може містити двокрапку.

Attr.localName

Частина назви після двокрапки, якщо вона є, інакше повна назва. Це атрибут лише для читання.

Attr.prefix

Частина назви перед двокрапкою, якщо вона є, інакше порожній рядок.

Attr.isId

Whether this attribute is of type ID, either because it is declared as such in the DTD or because Element.setIdAttribute() was used. This is a read-only attribute.

Attr.ownerElement

The Element node to which this attribute belongs, or None if it is not used. This is a read-only attribute.

Attr.specified

Whether the value of the attribute was explicitly set in the document, as opposed to being defaulted from the DTD. This is a read-only attribute.

Attr.value

The text value of the attribute. This is a synonym for the nodeValue attribute.

Об’єкти NamedNodeMap

NamedNodeMap не успадковує Node.

NamedNodeMap.length

Довжина списку атрибутів.

NamedNodeMap.item(index)

Return an attribute with a particular index. The order you get the attributes in is arbitrary but will be consistent for the life of a DOM. Each item is an attribute node. Get its value with the value attribute.

NamedNodeMap.getNamedItem(name)

Return the node with the given name, or None if there is no such node.

NamedNodeMap.getNamedItemNS(namespaceURI, localName)

Return the node with the given namespace URI and local name, or None if there is no such node.

NamedNodeMap.setNamedItem(node)

Add node to the map, using its name as the key. Return the node which it replaces, or None if it replaces no node.

NamedNodeMap.setNamedItemNS(node)

Add node to the map, using its namespace URI and local name as the key. Return the node which it replaces, or None if it replaces no node.

NamedNodeMap.removeNamedItem(name)

Remove and return the node with the given name. Raise NotFoundErr if there is no such node.

NamedNodeMap.removeNamedItemNS(namespaceURI, localName)

Remove and return the node with the given namespace URI and local name. Raise NotFoundErr if there is no such node.

You can also use the standardized getAttribute*() family of methods on the Element objects.

DocumentFragment Objects

DocumentFragment is a lightweight container of nodes. It is a subclass of Node. When it is inserted into the document tree, its children are inserted instead of it, and it becomes empty.

CharacterData Objects

CharacterData represents text-like data in the XML document. It is a subclass of Node, and the base class of Text, CDATASection and Comment. Such nodes cannot have child nodes.

CharacterData.data

The content of the node as a string.

CharacterData.length

The number of characters in data. This is a read-only attribute.

CharacterData.substringData(offset, count)

Return the substring of data of count characters starting at offset.

CharacterData.appendData(arg)

Append the string arg to data.

CharacterData.insertData(offset, arg)

Insert the string arg into data at offset.

CharacterData.deleteData(offset, count)

Remove count characters from data starting at offset.

CharacterData.replaceData(offset, count, arg)

Replace count characters of data starting at offset with the string arg.

Об’єкти коментарів

Comment represents a comment in the XML document. It is a subclass of CharacterData.

Comment.data

Вміст коментаря у вигляді рядка. Атрибут містить усі символи між початковими <!-- and trailing -->, але не включає їх.

Текст і об’єкти CDATASection

The Text interface represents text in the XML document. If the parser and DOM implementation support the DOM’s XML extension, portions of the text enclosed in CDATA marked sections are stored in CDATASection objects. These two interfaces are identical, but provide different values for the nodeType attribute.

Text extends the CharacterData interface, and CDATASection extends Text.

Text.data

Вміст текстового вузла у вигляді рядка.

Text.wholeText

The text of all Text nodes logically adjacent to this node, concatenated in document order. This is a read-only attribute.

Text.replaceWholeText(content)

Replace the text of all Text nodes logically adjacent to this node with content, removing the other nodes. Return this node, or None if content is empty.

Text.splitText(offset)

Split this node into two nodes at offset, keeping the first part in this node and returning a new sibling node with the rest.

Примітка

Використання вузла CDATASection не означає, що вузол представляє повний розділ, позначений CDATA, лише те, що вміст вузла був частиною розділу CDATA. Один розділ CDATA може бути представлений декількома вузлами в дереві документів. Немає способу визначити, чи два суміжні вузли CDATASection представляють різні розділи, позначені CDATA.

Об’єкти інструкцій обробки

Представляє інструкцію обробки в документі XML; це успадковує інтерфейс Node і не може мати дочірні вузли.

ProcessingInstruction.target

Вміст інструкції обробки до першого пробілу. Це атрибут лише для читання.

ProcessingInstruction.data

Вміст інструкції обробки після першого пробілу.

Entity Objects

Entity represents a parsed or unparsed entity declared in the DTD. It is a subclass of Node. Entity nodes are contained in DocumentType.entities and cannot be inserted into the document tree. The name of the entity is its nodeName.

Entity.publicId

The public identifier of the entity, or None if it is not specified. This is a read-only attribute.

Entity.systemId

The system identifier of the entity, or None if it is not specified. This is a read-only attribute.

Entity.notationName

The name of the notation for an unparsed entity, or None for a parsed entity. This is a read-only attribute.

Notation Objects

Notation represents a notation declared in the DTD. It is a subclass of Node and cannot have child nodes. Notation nodes are contained in DocumentType.notations and cannot be inserted into the document tree. The name of the notation is its nodeName.

Notation.publicId

The public identifier of the notation, or None if it is not specified. This is a read-only attribute.

Notation.systemId

The system identifier of the notation, or None if it is not specified. This is a read-only attribute.

Винятки

Рекомендація DOM рівня 2 визначає єдиний виняток, DOMException, і ряд констант, які дозволяють програмам визначити, який тип помилки сталася. Екземпляри DOMException містять атрибут code, який надає відповідне значення для конкретного винятку.

Інтерфейс Python DOM надає константи, але також розширює набір винятків, щоб для кожного з кодів винятків, визначених DOM, існував окремий виняток. Реалізації повинні викликати відповідні специфічні винятки, кожне з яких несе відповідне значення для атрибута code.

exception xml.dom.DOMException

Базовий клас винятків, який використовується для всіх конкретних винятків DOM. Цей клас винятків не можна створити безпосередньо.

exception xml.dom.DomstringSizeErr

Викликається, коли вказаний діапазон тексту не вміщується в рядок. Відомо, що це не використовується в реалізаціях Python DOM, але може бути отримано з реалізацій DOM, не написаних на Python.

exception xml.dom.HierarchyRequestErr

Викликається під час спроби вставити вузол у недозволений тип вузла.

exception xml.dom.IndexSizeErr

Викликається, коли параметр індексу або розміру методу від’ємний або перевищує допустимі значення.

exception xml.dom.InuseAttributeErr

Викликається, коли робиться спроба вставити вузол Attr, який уже присутній в іншому місці документа.

exception xml.dom.InvalidAccessErr

Викликається, якщо параметр або операція не підтримується на базовому об’єкті.

exception xml.dom.InvalidCharacterErr

Цей виняток виникає, коли рядковий параметр містить символ, який заборонено в контексті, у якому він використовується рекомендацією XML 1.0. Наприклад, спроба створити вузол Element із пробілом у назві типу елемента призведе до появи цієї помилки.

exception xml.dom.InvalidModificationErr

Викликається під час спроби змінити тип вузла.

exception xml.dom.InvalidStateErr

Викликається, коли робиться спроба використати об’єкт, який не визначено або більше не можна використовувати.

exception xml.dom.NamespaceErr

Якщо робиться спроба змінити будь-який об’єкт у спосіб, який заборонено щодо рекомендації Простори імен у XML, виникає цей виняток.

exception xml.dom.NotFoundErr

Виняток, коли вузол не існує в контексті посилання. Наприклад, NamedNodeMap.removeNamedItem() викличе це, якщо переданий вузол не існує на карті.

exception xml.dom.NotSupportedErr

Викликається, коли реалізація не підтримує потрібний тип об’єкта чи операції.

exception xml.dom.NoDataAllowedErr

Це виникає, якщо дані вказані для вузла, який не підтримує дані.

exception xml.dom.NoModificationAllowedErr

Викликається під час спроб модифікувати об’єкт, де модифікації заборонені (наприклад, для вузлів лише для читання).

exception xml.dom.SyntaxErr

Викликається, коли вказано недійсний або недопустимий рядок.

exception xml.dom.ValidationErr

Raised when an operation would make the document invalid with respect to partial validity. This is not known to be used in the Python DOM implementations, but may be received from DOM implementations not written in Python.

exception xml.dom.WrongDocumentErr

Викликається, коли вузол вставляється в документ, відмінний від того, якому він наразі належить, і реалізація не підтримує переміщення вузла з одного документа в інший.

Коди винятків, визначені в рекомендаціях DOM, відповідають описаним вище виняткам відповідно до цієї таблиці:

Постійний

Виняток

xml.dom.DOMSTRING_SIZE_ERR

DomstringSizeErr

xml.dom.HIERARCHY_REQUEST_ERR

HierarchyRequestErr

xml.dom.INDEX_SIZE_ERR

IndexSizeErr

xml.dom.INUSE_ATTRIBUTE_ERR

InuseAttributeErr

xml.dom.INVALID_ACCESS_ERR

InvalidAccessErr

xml.dom.INVALID_CHARACTER_ERR

InvalidCharacterErr

xml.dom.INVALID_MODIFICATION_ERR

InvalidModificationErr

xml.dom.INVALID_STATE_ERR

InvalidStateErr

xml.dom.NAMESPACE_ERR

NamespaceErr

xml.dom.NOT_FOUND_ERR

NotFoundErr

xml.dom.NOT_SUPPORTED_ERR

NotSupportedErr

xml.dom.NO_DATA_ALLOWED_ERR

NoDataAllowedErr

xml.dom.NO_MODIFICATION_ALLOWED_ERR

NoModificationAllowedErr

xml.dom.SYNTAX_ERR

SyntaxErr

xml.dom.VALIDATION_ERR

ValidationErr

xml.dom.WRONG_DOCUMENT_ERR

WrongDocumentErr

Відповідність

У цьому розділі описано вимоги до відповідності та зв’язки між Python DOM API, рекомендаціями W3C DOM і відображенням OMG IDL для Python.

Відображення типу

Типи IDL, які використовуються в специфікації DOM, зіставляються з типами Python відповідно до наступної таблиці.

Тип IDL

Тип Python

логічний

bool або int

int

int

long int

int

unsigned int

int

DOMString

str або bytes

нуль

Жодного

Методи доступу

Відображення з OMG IDL на Python визначає функції доступу для оголошень атрибутів IDL майже так само, як це робить відображення Java. Відображення декларацій IDL

readonly attribute string someValue;
         attribute string anotherValue;

yields three accessor functions: a «get» method for someValue (_get_someValue()), and «get» and «set» methods for anotherValue (_get_anotherValue() and _set_anotherValue()). The mapping, in particular, does not require that the IDL attributes are accessible as normal Python attributes: object.someValue is not required to work, and may raise an AttributeError.

Однак Python DOM API не вимагає, щоб звичайний доступ до атрибутів працював. Це означає, що типові сурогати, згенеровані компіляторами Python IDL, навряд чи працюватимуть, і об’єкти-огортки можуть знадобитися на клієнті, якщо доступ до об’єктів DOM здійснюється через CORBA. Хоча для клієнтів CORBA DOM це вимагає додаткового розгляду, розробники з досвідом використання DOM поверх CORBA з Python не вважають це проблемою. Атрибути, оголошені лише для читання, можуть не обмежувати доступ для запису в усіх реалізаціях DOM.

В Python DOM API функції доступу не потрібні. Якщо вони надані, вони мають приймати форму, визначену відображенням Python IDL, але ці методи вважаються непотрібними, оскільки атрибути доступні безпосередньо з Python. Аксесори «Set» ніколи не повинні надаватися для атрибутів «лише для читання».

The IDL definitions do not fully embody the requirements of the W3C DOM API, such as the notion of certain objects, such as the return value of getElementsByTagName(), being «live». The Python DOM API does not require implementations to enforce such requirements.