xml.dom --- ドキュメントオブジェクトモデル API

ソースコード: Lib/xml/dom/__init__.py


文書オブジェクトモデル (Document Object Model)、すなわち "DOM" は、ワールドワイドウェブコンソーシアム (World Wide Web Consortium, W3C) による、XML ドキュメントにアクセスしたり変更を加えたりするための、プログラミング言語間共通の API です。DOM 実装によって、XML ドキュメントはツリー構造として表現されます。また、クライアントコード側でツリー構造をゼロから構築できるようになります。さらに、前述の構造に対して、よく知られたインターフェースをもつ一連のオブジェクトを通したアクセス手段も提供します。

DOM はランダムアクセスを行うアプリケーションで非常に有用です。SAX では、一度に閲覧することができるのはドキュメントのほんの一部分です。ある SAX 要素に注目している際には、別の要素をアクセスすることはできません。またテキストノードに注目しているときには、その中に入っている要素をアクセスすることができません。SAX によるアプリケーションを書くときには、プログラムがドキュメント内のどこを処理しているのかを追跡するよう、コードのどこかに記述する必要があります。SAX 自体がその作業を行ってくれることはありません。さらに、XML ドキュメントに対する先読み (look ahead) が必要だとすると不運なことになります。

アプリケーションによっては、ツリーにアクセスできなければイベント駆動モデルを実現できません。もちろん、何らかのツリーを SAX イベントに応じて自分で構築することもできるでしょうが、DOM ではそのようなコードを書かなくてもよくなります。DOM は XML データに対する標準的なツリー表現なのです。

文書オブジェクトモデルは、W3C によっていくつかの段階、W3C の用語で言えば "レベル (level)" で定義されています。Python においては、DOM API への対応付けは実質的には DOM レベル 2 勧告に基づいています。

DOM アプリケーションは、普通は XML を DOM に解析するところから始まります。どのようにして解析を行うかについては DOM レベル 1 では全くカバーしておらず、レベル 2 では限定的な改良だけが行われました: レベル 2 では Document を生成するメソッドを提供する DOMImplementation オブジェクトクラスがありますが、実装に依存しない方法で XML リーダ(reader)/パーザ(parser)/文書ビルダ (Document builder) にアクセスする方法はありません。また、既存の Document オブジェクトなしにこれらのメソッドにアクセスするような、よく定義された方法もありません。 Python では、各々の DOM 実装で getDOMImplementation() が定義されているはずです。 DOM レベル 3 ではロード(Load)/ストア(Store) 仕様が追加され、リーダのインターフェースにを定義していますが、Python 標準ライブラリではまだ利用することができません。

DOM 文書オブジェクトを生成したら、そのプロパティとメソッドを使って XML 文書の一部にアクセスできます。これらのプロパティは DOM 仕様で定義されています; 本リファレンスマニュアルでは、Python において DOM 仕様がどのように解釈されているかを記述しています。

W3C から提供されている仕様は、 DOM API を Java、ECMAScript、および OMG IDL で定義しています。ここで定義されている Python での対応づけは、大部分がこの仕様の IDL 版に基づいていますが、厳密な準拠は必要とされていません (実装で IDL の厳密な対応付けをサポートするのは自由ですが)。API への対応付けに関する詳細な議論は 適合性 を参照してください。

参考

Document Object Model (DOM) Level 2 Specification

Python DOM API が準拠している W3C 勧告。

Document Object Model (DOM) Level 1 Specification

xml.dom.minidom でサポートされている W3C の DOM に関する勧告。

Python Language Mapping Specification

このドキュメントでは OMG IDL から Python への対応付けを記述しています。

モジュールコンテンツ

xml.dom には以下の関数があります:

xml.dom.registerDOMImplementation(name, factory)

ファクトリ関数 (factory function) 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

Namespaces in XML (4 節) で定義されている、予約済みプレフィクス (reserved prefix) xml に関連付けられた名前空間 URI です。

xml.dom.XMLNS_NAMESPACE

Document Object Model (DOM) Level 2 Core Specification (1.1.8 節) で定義されている、名前空間宣言への名前空間 URI です。

xml.dom.XHTML_NAMESPACE

XHTML 1.0: The Extensible HyperText Markup Language (3.1.1 節) で定義されている、XHTML 名前空間 URI です。

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 について最も明確に限定しているドキュメントは W3C による DOM 仕様です。

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 属性は単純な文字列としてだけではなく、ノードとして操作されるかもしれないので注意してください。とはいえ、そうしなければならない場合はかなり稀なので、今のところ記述されていません。

インターフェース

目的

DOMImplementation

DOMImplementation オブジェクト

根底にある実装へのインターフェース。

Node

Node オブジェクト

ドキュメント内の大部分のオブジェクトに対する基底インターフェース。

NodeList

NodeList オブジェクト

ノード列に対するインターフェース。

DocumentType

DocumentType オブジェクト

ドキュメントの処理に必要な宣言についての情報。

Document

Document オブジェクト

ドキュメント全体を表現するオブジェクト。

Element

Element オブジェクト

ドキュメント階層内の要素ノード。

Attr

Attr オブジェクト

要素ノード上の属性値ノード。

Comment

Comment オブジェクト

ソースドキュメント内のコメント表現。

Text

Text オブジェクトおよび CDATASection オブジェクト

ドキュメント内のテキスト記述を含むノード。

ProcessingInstruction

ProcessingInstruction オブジェクト

処理命令 (processing instruction) 表現。

さらに追加の節として、Python で DOM を利用するために定義されている例外について記述しています。

DOMImplementation オブジェクト

DOMImplementation インターフェースは、利用している DOM 実装において特定の機能が利用可能かどうかを決定するための方法をアプリケーションに提供します。DOM レベル 2 では、 DOMImplementation を使って新たな Document オブジェクトや DocumentType オブジェクトを生成する機能も追加しています。

DOMImplementation.hasFeature(feature, version)

機能名 feature とバージョン番号 version で識別される機能(feature)が実装されていれば True を返します。

DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)

新たな(DOMのスーパークラスである) Document クラスのオブジェクトを返します。このクラスは namespaceUriqualifiedName が設定された子クラス Element のオブジェクトを所有しています。 doctypecreateDocumentType() によって生成された DocumentType クラスのオブジェクト、または None である必要があります。 Python DOM APIでは、子クラスである Element を作成しないことを示すために、はじめの2つの引数を None に設定することができます。

DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)

新たな DocumentType クラスのオブジェクトを返します。このオブジェクトは qualifiedNamepublicId 、そして 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 ノードの場合、この値はルート要素 (root element) の場合を除き親要素 (parent element) となり、ルート要素の場合には Document オブジェクトとなります。 Attr ノードの場合、この値は常に None となります。読み出し専用の属性です。

Node.attributes

属性オブジェクトの NamedNodeMap です。要素だけがこの属性に実際の値を持ちます; その他のオブジェクトでは、この属性を None にします。読み出し専用の属性です。

Node.previousSibling

このノードと同じ親ノードを持ち、直前にくるノードです。例えば、self 要素の開始タグの直前にくる終了タグを持つ要素です。もちろん、XML 文書は要素だけで構成されているだけではないので、直前にくる兄弟関係にある要素 (sibling) はテキストやコメント、その他になる可能性があります。このノードが親ノードにおける先頭の子ノードである場合、属性値は 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'

None

DocumentFragment

'#document-fragment'

None

DocumentType

name

None

Element

tagName

None

Entity

the name of the entity

None

Notation

the name of the notation

None

ProcessingInstruction

target

data

Text

'#text'

the content

Node.hasAttributes()

ノードが何らかの属性を持っている場合に True を返します。

Node.hasChildNodes()

ノードが何らかの子ノードを持っている場合に True を返します。

Node.isSameNode(other)

other がこのノードと同じノードを参照している場合に True を返します。このメソッドは、何らかのプロキシ (proxy) 機構を利用するような DOM 実装で特に便利です (一つ以上のオブジェクトが同じノードを参照するかもしれないからです)。

注釈

このメソッドは DOM レベル 3 API の提案に基づいたもので、まだ "ワーキングドラフト(working draft)" の段階です。しかし、このインターフェースには異論は出ないと考えられます。W3C による変更があっても、必ずしも Python DOM インターフェースにおけるこのメソッドに影響するとは限りません (ただしこのメソッドに対する何らかの新しい W3C API もサポートされるかもしれません)。

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)

このノードを複製 (clone) します。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

シーケンス中のノードの数です。

この他に、Python の DOM インターフェースでは、 NodeList オブジェクトを Python のシーケンスとして使えるようにするサポートが追加されていることが必要です。 NodeList の実装では、全て __len__()__getitem__() をサポートしなければなりません; このサポートにより、 for 文内で NodeList にわたる繰り返しと、組み込み関数 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.

DocumentTypeNode を特殊化したもので、以下の属性を加えています:

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 オブジェクト

Document は XML ドキュメント全体を表現し、その構成要素である要素、属性、処理命令、コメント等を持ちます。 DocumentNode からプロパティを継承していることを思い出してください。

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)

引数として渡されたデータの入ったテキストノードを生成して返します。他の生成 (create) メソッドと同じく、このメソッドは生成されたノードをツリーに挿入しません。

Document.createComment(data)

引数として渡されたデータの入ったコメントノードを生成して返します。他の生成 (create) メソッドと同じく、このメソッドは生成されたノードをツリーに挿入しません。

Document.createProcessingInstruction(target, data)

引数として渡された target および data の入った処理命令ノードを生成して返します。他の生成 (create) メソッドと同じく、このメソッドは生成されたノードをツリーに挿入しません。

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 とローカル名 (local name) を持つものを検索します。ローカル名は名前空間における接頭辞以降の部分です。

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 オブジェクト

ElementNode のサブクラスです。このため 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)

指定要素に name で渡した名前の属性が存在していれば True を返します。

Element.hasAttributeNS(namespaceURI, localName)

指定要素に namespaceURIlocalName で指定した名前の属性が存在していれば True を返します。

Element.getAttribute(name)

name で指定した属性の値を文字列として返します。もし、属性が存在しない、もしくは属性に値が設定されていない場合、空の文字列が返されます。

Element.getAttributeNode(attrname)

attrname で指定された属性の Attr ノードを返します。

Element.getAttributeNS(namespaceURI, localName)

namespaceURIlocalName によって指定した属性の値を文字列として返します。もし、属性が存在しない、もしくは属性に値が設定されていない場合、空の文字列が返されます。

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 オブジェクト

AttrNode を継承しており、全ての属性を継承しています。

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 Objects

NamedNodeMapNode を継承して いません

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 オブジェクト

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

Comment.data

文字列によるコメントの内容です。この属性には、コメントの先頭にある <!- - と末尾にある - -> 間の全ての文字が入っていますが、<!- -- -> 自体は含みません。

Text オブジェクトおよび 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 マーク区域かどうかを決定する方法はありません。

ProcessingInstruction オブジェクト

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 で定義されている各例外コードに対して特定の例外が存在するようにしています。 DOM の実装では、適切な特定の例外を送出しなければならず、各例外は code 属性に対応する適切な値を伴わなければなりません。

exception xml.dom.DOMException

全ての特定の DOM 例外で使われている基底例外クラスです。この例外クラスを直接インスタンス化することはできません。

exception xml.dom.DomstringSizeErr

指定された範囲のテキストが文字列に収まらない場合に送出されます。この例外は Python の DOM 実装で使われるかどうかは判っていませんが、Python で書かれていない DOM 実装から送出される場合があります。

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

Namespaces in 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 API への対応付けとの間の関係について述べます。

型の対応付け

DOM 仕様で使われている IDL 型は、以下のテーブルに従って Python の型に対応付けられています。

IDL 型

Python の型

boolean

bool または int

int

int

long int

int

unsigned int

int

DOMString

str または bytes

null

None

アクセサメソッド

OMG IDL から Python への対応付けは、IDL attribute 宣言へのアクセサ関数の定義を、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 クライアントでは他にもいくつか考慮すべきことがある一方で、Python から CORBA を介して DOM を使った経験を持つ実装者はこのことを問題視していません。readonly であると宣言された属性は、全ての DOM 実装で書き込みアクセスを制限しているとは限りません。

Python DOM API では、アクセサ関数は必須ではありません。アクセサ関数が提供された場合、Python IDL 対応付けによって定義された形式をとらなければなりませんが、属性は Python から直接アクセスすることができるので、それらのメソッドは必須ではないと考えられます。readonly であると宣言された属性に対しては、 "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.