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 notNone, imports the corresponding module and returns aDOMImplementationobject if the import succeeds. If no name is given, and if the environment variablePYTHON_DOMis set, this variable is used to find the implementation. The only well-known name in the standard library is'minidom', forxml.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 thehasFeature()method on availableDOMImplementationobjects.
Також надано деякі зручні константи:
- 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
namespaceURIof 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 також можна використовувати як вузли, а не як прості рядки. Однак це доводиться робити досить рідко, тому таке використання ще не задокументовано.
Інтерфейс |
Розділ |
призначення |
|---|---|---|
|
Інтерфейс базової реалізації. |
|
Базовий інтерфейс для більшості об’єктів у документі. |
||
Інтерфейс для послідовності вузлів. |
||
Інформація про декларації, необхідні для оформлення документа. |
||
Об’єкт, який представляє весь документ. |
||
Вузли елементів в ієрархії документа. |
||
Вузли значення атрибута на вузлах елемента. |
||
Відображення коментарів у вихідному документі. |
||
Вузли, що містять текстовий вміст із документа. |
||
Представлення інструкцій обробки. |
Додатковий розділ описує винятки, визначені для роботи з 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:
Documentat most one
Element, at most oneDocumentType,ProcessingInstructionandCommentDocumentFragmentandElementElement,Text,CDATASection,ProcessingInstructionandCommentAttr
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
Nodeobject. 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
nodeTypeattribute.
- 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
NodeListof 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
tagNamefollowing the colon if there is one, else the entiretagName. The value is a string.
- Node.prefix¶
The part of the
tagNamepreceding the colon if there is one, else the empty string. The value is a string, orNone.
- Node.namespaceURI¶
Простір імен, пов’язаний з іменем елемента. Це буде рядок або
None. Це атрибут лише для читання.
- Node.ownerDocument¶
The
Documentobject to which this node belongs, orNonefor 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 isNone, the association is removed. handler is called when the node is cloned, imported, renamed or deleted; passNoneif no notification is needed.
- Node.getUserData(key)¶
Return the data associated with key on this node by
setUserData(), orNone.
- 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
tagNameproperty for elements or thenameproperty 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 |
|---|---|---|
|
the content |
|
|
the content |
|
|
|
|
|
|
|
|
||
|
||
the name of the entity |
|
|
the name of the notation |
|
|
|
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,
NotFoundErris raised. newChild is returned. If refChild isNone, 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,
NotFoundErris raised. oldChild is returned on success. If oldChild will not be used further, itsunlink()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,
NotFoundErris 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
Noneif 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
Noneif theDOCTYPEdeclaration does not specify it.
- DocumentType.systemId¶
The system identifier, a URI, for the external subset of the document type definition, or
Noneif theDOCTYPEdeclaration does not specify it.
- DocumentType.internalSubset¶
Рядок, що містить повну внутрішню частину документа. Це не включає дужки, які містять підмножину. Якщо документ не має внутрішньої підмножини, це має бути
None.
- DocumentType.name¶
Ім’я кореневого елемента, указане в декларації
DOCTYPE, якщо воно є.
- DocumentType.entities¶
This is a
NamedNodeMapofEntitynodes 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 beNoneif the information is not provided by the parser, or if no entities are defined.
- DocumentType.notations¶
This is a
NamedNodeMapofNotationnodes 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 beNoneif the information is not provided by the parser, or if no notations are defined.
Об’єкти документа¶
Document представляє весь XML-документ, включаючи його складові елементи, атрибути, інструкції з обробки, коментарі тощо. Пам’ятайте, що він успадковує властивості від Node.
- Document.documentElement¶
Єдиний кореневий елемент документа.
- Document.doctype¶
The
DocumentTypenode of the document, orNone. This is a read-only attribute.
- Document.implementation¶
The
DOMImplementationobject 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
Noneif it is unknown.
- Document.createDocumentFragment()¶
Create and return an empty
DocumentFragmentnode.
- Document.createCDATASection(data)¶
Create and return a
CDATASectionnode 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()orappendChild().
- 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()orappendChild().
- 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 appropriateElementobject 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 appropriateElementobject 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 byElement.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_NAMESPACEif the node does not belong to a namespace. name is the new qualified name.Raise
WrongDocumentErrif n was created by another document, andNotSupportedErrif 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(). RaiseNotFoundErrif 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.getElementsByTagNameNS(namespaceURI, localName)¶
Те саме, що еквівалентний метод у класі
Document.
- Element.hasAttribute(name)¶
Повертає
True, якщо елемент має атрибут із назвою name.
- Element.hasAttributeNS(namespaceURI, localName)¶
Повертає
True, якщо елемент має атрибут, названий namespaceURI і localName.
- Element.getAttribute(name)¶
Повертає значення атрибута з іменем name у вигляді рядка. Якщо такий атрибут не існує, повертається порожній рядок, як якщо б атрибут не мав значення.
- 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
nameattribute matches. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use,InuseAttributeErrwill be raised.
- Element.setAttributeNodeNS(newAttr)¶
Add a new attribute node to the element, replacing an existing attribute if necessary if the
namespaceURIandlocalNameattributes match. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use,InuseAttributeErrwill 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
Elementnode to which this attribute belongs, orNoneif 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.
Об’єкти 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
valueattribute.
- NamedNodeMap.getNamedItem(name)¶
Return the node with the given
name, orNoneif there is no such node.
- NamedNodeMap.getNamedItemNS(namespaceURI, localName)¶
Return the node with the given namespace URI and local name, or
Noneif there is no such node.
- NamedNodeMap.setNamedItem(node)¶
Add node to the map, using its
nameas the key. Return the node which it replaces, orNoneif 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
Noneif it replaces no node.
- NamedNodeMap.removeNamedItem(name)¶
Remove and return the node with the given
name. RaiseNotFoundErrif there is no such node.
- NamedNodeMap.removeNamedItemNS(namespaceURI, localName)¶
Remove and return the node with the given namespace URI and local name. Raise
NotFoundErrif 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.
Текст і об’єкти 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
Textnodes logically adjacent to this node, concatenated in document order. This is a read-only attribute.
- Text.replaceWholeText(content)¶
Replace the text of all
Textnodes logically adjacent to this node with content, removing the other nodes. Return this node, orNoneif 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
Noneif it is not specified. This is a read-only attribute.
- Entity.systemId¶
The system identifier of the entity, or
Noneif it is not specified. This is a read-only attribute.
- Entity.notationName¶
The name of the notation for an unparsed entity, or
Nonefor 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
Noneif it is not specified. This is a read-only attribute.
- Notation.systemId¶
The system identifier of the notation, or
Noneif 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, відповідають описаним вище виняткам відповідно до цієї таблиці:
Постійний |
Виняток |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Відповідність¶
У цьому розділі описано вимоги до відповідності та зв’язки між Python DOM API, рекомендаціями W3C DOM і відображенням OMG IDL для Python.
Відображення типу¶
Типи IDL, які використовуються в специфікації DOM, зіставляються з типами Python відповідно до наступної таблиці.
Тип IDL |
Тип Python |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Методи доступу¶
Відображення з 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.
Об’єкти коментарів¶
Commentrepresents a comment in the XML document. It is a subclass ofCharacterData.Вміст коментаря у вигляді рядка. Атрибут містить усі символи між початковими
<!--and trailing-->, але не включає їх.