blob: 45d30d67299f4b732b99072645ed1000074b9457 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`xml.dom` --- The Document Object Model API
2================================================
3
4.. module:: xml.dom
5 :synopsis: Document Object Model API for Python.
6.. sectionauthor:: Paul Prescod <paul@prescod.net>
7.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>
8
9
Georg Brandl116aa622007-08-15 14:28:22 +000010The Document Object Model, or "DOM," is a cross-language API from the World Wide
11Web Consortium (W3C) for accessing and modifying XML documents. A DOM
12implementation presents an XML document as a tree structure, or allows client
13code to build such a structure from scratch. It then gives access to the
14structure through a set of objects which provided well-known interfaces.
15
16The DOM is extremely useful for random-access applications. SAX only allows you
17a view of one bit of the document at a time. If you are looking at one SAX
18element, you have no access to another. If you are looking at a text node, you
19have no access to a containing element. When you write a SAX application, you
20need to keep track of your program's position in the document somewhere in your
21own code. SAX does not do it for you. Also, if you need to look ahead in the
22XML document, you are just out of luck.
23
24Some applications are simply impossible in an event driven model with no access
25to a tree. Of course you could build some sort of tree yourself in SAX events,
26but the DOM allows you to avoid writing that code. The DOM is a standard tree
27representation for XML data.
28
29The Document Object Model is being defined by the W3C in stages, or "levels" in
30their terminology. The Python mapping of the API is substantially based on the
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000031DOM Level 2 recommendation.
32
33.. XXX PyXML is dead...
34.. The mapping of the Level 3 specification, currently
35 only available in draft form, is being developed by the `Python XML Special
36 Interest Group <http://www.python.org/sigs/xml-sig/>`_ as part of the `PyXML
37 package <http://pyxml.sourceforge.net/>`_. Refer to the documentation bundled
38 with that package for information on the current state of DOM Level 3 support.
Georg Brandl116aa622007-08-15 14:28:22 +000039
Christian Heimes5b5e81c2007-12-31 16:14:33 +000040.. What if your needs are somewhere between SAX and the DOM? Perhaps
41 you cannot afford to load the entire tree in memory but you find the
42 SAX model somewhat cumbersome and low-level. There is also a module
43 called xml.dom.pulldom that allows you to build trees of only the
44 parts of a document that you need structured access to. It also has
45 features that allow you to find your way around the DOM.
46 See http://www.prescod.net/python/pulldom
Georg Brandl116aa622007-08-15 14:28:22 +000047
48DOM applications typically start by parsing some XML into a DOM. How this is
49accomplished is not covered at all by DOM Level 1, and Level 2 provides only
50limited improvements: There is a :class:`DOMImplementation` object class which
51provides access to :class:`Document` creation methods, but no way to access an
52XML reader/parser/Document builder in an implementation-independent way. There
53is also no well-defined way to access these methods without an existing
54:class:`Document` object. In Python, each DOM implementation will provide a
55function :func:`getDOMImplementation`. DOM Level 3 adds a Load/Store
56specification, which defines an interface to the reader, but this is not yet
57available in the Python standard library.
58
59Once you have a DOM document object, you can access the parts of your XML
60document through its properties and methods. These properties are defined in
61the DOM specification; this portion of the reference manual describes the
62interpretation of the specification in Python.
63
64The specification provided by the W3C defines the DOM API for Java, ECMAScript,
65and OMG IDL. The Python mapping defined here is based in large part on the IDL
66version of the specification, but strict compliance is not required (though
67implementations are free to support the strict mapping from IDL). See section
68:ref:`dom-conformance` for a detailed discussion of mapping requirements.
69
70
71.. seealso::
72
73 `Document Object Model (DOM) Level 2 Specification <http://www.w3.org/TR/DOM-Level-2-Core/>`_
74 The W3C recommendation upon which the Python DOM API is based.
75
76 `Document Object Model (DOM) Level 1 Specification <http://www.w3.org/TR/REC-DOM-Level-1/>`_
77 The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`.
78
Benjamin Peterson39778f62009-11-25 18:37:12 +000079 `Python Language Mapping Specification <http://www.omg.org/spec/PYTH/1.2/PDF>`_
Georg Brandl116aa622007-08-15 14:28:22 +000080 This specifies the mapping from OMG IDL to Python.
81
82
83Module Contents
84---------------
85
86The :mod:`xml.dom` contains the following functions:
87
88
89.. function:: registerDOMImplementation(name, factory)
90
91 Register the *factory* function with the name *name*. The factory function
92 should return an object which implements the :class:`DOMImplementation`
93 interface. The factory function can return the same object every time, or a new
94 one for each call, as appropriate for the specific implementation (e.g. if that
95 implementation supports some customization).
96
97
Georg Brandlb044b2a2009-09-16 16:05:59 +000098.. function:: getDOMImplementation(name=None, features=())
Georg Brandl116aa622007-08-15 14:28:22 +000099
100 Return a suitable DOM implementation. The *name* is either well-known, the
101 module name of a DOM implementation, or ``None``. If it is not ``None``, imports
102 the corresponding module and returns a :class:`DOMImplementation` object if the
103 import succeeds. If no name is given, and if the environment variable
104 :envvar:`PYTHON_DOM` is set, this variable is used to find the implementation.
105
106 If name is not given, this examines the available implementations to find one
107 with the required feature set. If no implementation can be found, raise an
108 :exc:`ImportError`. The features list must be a sequence of ``(feature,
109 version)`` pairs which are passed to the :meth:`hasFeature` method on available
110 :class:`DOMImplementation` objects.
111
112Some convenience constants are also provided:
113
114
115.. data:: EMPTY_NAMESPACE
116
117 The value used to indicate that no namespace is associated with a node in the
118 DOM. This is typically found as the :attr:`namespaceURI` of a node, or used as
119 the *namespaceURI* parameter to a namespaces-specific method.
120
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122.. data:: XML_NAMESPACE
123
124 The namespace URI associated with the reserved prefix ``xml``, as defined by
125 `Namespaces in XML <http://www.w3.org/TR/REC-xml-names/>`_ (section 4).
126
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128.. data:: XMLNS_NAMESPACE
129
130 The namespace URI for namespace declarations, as defined by `Document Object
131 Model (DOM) Level 2 Core Specification
132 <http://www.w3.org/TR/DOM-Level-2-Core/core.html>`_ (section 1.1.8).
133
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135.. data:: XHTML_NAMESPACE
136
137 The URI of the XHTML namespace as defined by `XHTML 1.0: The Extensible
138 HyperText Markup Language <http://www.w3.org/TR/xhtml1/>`_ (section 3.1.1).
139
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141In addition, :mod:`xml.dom` contains a base :class:`Node` class and the DOM
142exception classes. The :class:`Node` class provided by this module does not
143implement any of the methods or attributes defined by the DOM specification;
144concrete DOM implementations must provide those. The :class:`Node` class
145provided as part of this module does provide the constants used for the
146:attr:`nodeType` attribute on concrete :class:`Node` objects; they are located
147within the class rather than at the module level to conform with the DOM
148specifications.
149
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000150.. Should the Node documentation go here?
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152
153.. _dom-objects:
154
155Objects in the DOM
156------------------
157
158The definitive documentation for the DOM is the DOM specification from the W3C.
159
160Note that DOM attributes may also be manipulated as nodes instead of as simple
161strings. It is fairly rare that you must do this, however, so this usage is not
162yet documented.
163
164+--------------------------------+-----------------------------------+---------------------------------+
165| Interface | Section | Purpose |
166+================================+===================================+=================================+
167| :class:`DOMImplementation` | :ref:`dom-implementation-objects` | Interface to the underlying |
168| | | implementation. |
169+--------------------------------+-----------------------------------+---------------------------------+
170| :class:`Node` | :ref:`dom-node-objects` | Base interface for most objects |
171| | | in a document. |
172+--------------------------------+-----------------------------------+---------------------------------+
173| :class:`NodeList` | :ref:`dom-nodelist-objects` | Interface for a sequence of |
174| | | nodes. |
175+--------------------------------+-----------------------------------+---------------------------------+
176| :class:`DocumentType` | :ref:`dom-documenttype-objects` | Information about the |
177| | | declarations needed to process |
178| | | a document. |
179+--------------------------------+-----------------------------------+---------------------------------+
180| :class:`Document` | :ref:`dom-document-objects` | Object which represents an |
181| | | entire document. |
182+--------------------------------+-----------------------------------+---------------------------------+
183| :class:`Element` | :ref:`dom-element-objects` | Element nodes in the document |
184| | | hierarchy. |
185+--------------------------------+-----------------------------------+---------------------------------+
186| :class:`Attr` | :ref:`dom-attr-objects` | Attribute value nodes on |
187| | | element nodes. |
188+--------------------------------+-----------------------------------+---------------------------------+
189| :class:`Comment` | :ref:`dom-comment-objects` | Representation of comments in |
190| | | the source document. |
191+--------------------------------+-----------------------------------+---------------------------------+
192| :class:`Text` | :ref:`dom-text-objects` | Nodes containing textual |
193| | | content from the document. |
194+--------------------------------+-----------------------------------+---------------------------------+
195| :class:`ProcessingInstruction` | :ref:`dom-pi-objects` | Processing instruction |
196| | | representation. |
197+--------------------------------+-----------------------------------+---------------------------------+
198
199An additional section describes the exceptions defined for working with the DOM
200in Python.
201
202
203.. _dom-implementation-objects:
204
205DOMImplementation Objects
206^^^^^^^^^^^^^^^^^^^^^^^^^
207
208The :class:`DOMImplementation` interface provides a way for applications to
209determine the availability of particular features in the DOM they are using.
210DOM Level 2 added the ability to create new :class:`Document` and
211:class:`DocumentType` objects using the :class:`DOMImplementation` as well.
212
213
214.. method:: DOMImplementation.hasFeature(feature, version)
215
216 Return true if the feature identified by the pair of strings *feature* and
217 *version* is implemented.
218
219
220.. method:: DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)
221
222 Return a new :class:`Document` object (the root of the DOM), with a child
223 :class:`Element` object having the given *namespaceUri* and *qualifiedName*. The
224 *doctype* must be a :class:`DocumentType` object created by
225 :meth:`createDocumentType`, or ``None``. In the Python DOM API, the first two
226 arguments can also be ``None`` in order to indicate that no :class:`Element`
227 child is to be created.
228
229
230.. method:: DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)
231
232 Return a new :class:`DocumentType` object that encapsulates the given
233 *qualifiedName*, *publicId*, and *systemId* strings, representing the
234 information contained in an XML document type declaration.
235
236
237.. _dom-node-objects:
238
239Node Objects
240^^^^^^^^^^^^
241
242All of the components of an XML document are subclasses of :class:`Node`.
243
244
245.. attribute:: Node.nodeType
246
247 An integer representing the node type. Symbolic constants for the types are on
248 the :class:`Node` object: :const:`ELEMENT_NODE`, :const:`ATTRIBUTE_NODE`,
249 :const:`TEXT_NODE`, :const:`CDATA_SECTION_NODE`, :const:`ENTITY_NODE`,
250 :const:`PROCESSING_INSTRUCTION_NODE`, :const:`COMMENT_NODE`,
251 :const:`DOCUMENT_NODE`, :const:`DOCUMENT_TYPE_NODE`, :const:`NOTATION_NODE`.
252 This is a read-only attribute.
253
254
255.. attribute:: Node.parentNode
256
257 The parent of the current node, or ``None`` for the document node. The value is
258 always a :class:`Node` object or ``None``. For :class:`Element` nodes, this
259 will be the parent element, except for the root element, in which case it will
260 be the :class:`Document` object. For :class:`Attr` nodes, this is always
261 ``None``. This is a read-only attribute.
262
263
264.. attribute:: Node.attributes
265
266 A :class:`NamedNodeMap` of attribute objects. Only elements have actual values
267 for this; others provide ``None`` for this attribute. This is a read-only
268 attribute.
269
270
271.. attribute:: Node.previousSibling
272
273 The node that immediately precedes this one with the same parent. For
274 instance the element with an end-tag that comes just before the *self*
275 element's start-tag. Of course, XML documents are made up of more than just
276 elements so the previous sibling could be text, a comment, or something else.
277 If this node is the first child of the parent, this attribute will be
278 ``None``. This is a read-only attribute.
279
280
281.. attribute:: Node.nextSibling
282
283 The node that immediately follows this one with the same parent. See also
284 :attr:`previousSibling`. If this is the last child of the parent, this
285 attribute will be ``None``. This is a read-only attribute.
286
287
288.. attribute:: Node.childNodes
289
290 A list of nodes contained within this node. This is a read-only attribute.
291
292
293.. attribute:: Node.firstChild
294
295 The first child of the node, if there are any, or ``None``. This is a read-only
296 attribute.
297
298
299.. attribute:: Node.lastChild
300
301 The last child of the node, if there are any, or ``None``. This is a read-only
302 attribute.
303
304
305.. attribute:: Node.localName
306
307 The part of the :attr:`tagName` following the colon if there is one, else the
308 entire :attr:`tagName`. The value is a string.
309
310
311.. attribute:: Node.prefix
312
313 The part of the :attr:`tagName` preceding the colon if there is one, else the
314 empty string. The value is a string, or ``None``
315
316
317.. attribute:: Node.namespaceURI
318
319 The namespace associated with the element name. This will be a string or
320 ``None``. This is a read-only attribute.
321
322
323.. attribute:: Node.nodeName
324
325 This has a different meaning for each node type; see the DOM specification for
326 details. You can always get the information you would get here from another
327 property such as the :attr:`tagName` property for elements or the :attr:`name`
328 property for attributes. For all node types, the value of this attribute will be
329 either a string or ``None``. This is a read-only attribute.
330
331
332.. attribute:: Node.nodeValue
333
334 This has a different meaning for each node type; see the DOM specification for
335 details. The situation is similar to that with :attr:`nodeName`. The value is
336 a string or ``None``.
337
338
339.. method:: Node.hasAttributes()
340
341 Returns true if the node has any attributes.
342
343
344.. method:: Node.hasChildNodes()
345
346 Returns true if the node has any child nodes.
347
348
349.. method:: Node.isSameNode(other)
350
351 Returns true if *other* refers to the same node as this node. This is especially
352 useful for DOM implementations which use any sort of proxy architecture (because
353 more than one object can refer to the same node).
354
355 .. note::
356
357 This is based on a proposed DOM Level 3 API which is still in the "working
358 draft" stage, but this particular interface appears uncontroversial. Changes
359 from the W3C will not necessarily affect this method in the Python DOM interface
360 (though any new W3C API for this would also be supported).
361
362
363.. method:: Node.appendChild(newChild)
364
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000365 Add a new child node to this node at the end of the list of
366 children, returning *newChild*. If the node was already in
367 in the tree, it is removed first.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369
370.. method:: Node.insertBefore(newChild, refChild)
371
372 Insert a new child node before an existing child. It must be the case that
373 *refChild* is a child of this node; if not, :exc:`ValueError` is raised.
374 *newChild* is returned. If *refChild* is ``None``, it inserts *newChild* at the
375 end of the children's list.
376
377
378.. method:: Node.removeChild(oldChild)
379
380 Remove a child node. *oldChild* must be a child of this node; if not,
381 :exc:`ValueError` is raised. *oldChild* is returned on success. If *oldChild*
382 will not be used further, its :meth:`unlink` method should be called.
383
384
385.. method:: Node.replaceChild(newChild, oldChild)
386
387 Replace an existing node with a new node. It must be the case that *oldChild*
388 is a child of this node; if not, :exc:`ValueError` is raised.
389
390
391.. method:: Node.normalize()
392
393 Join adjacent text nodes so that all stretches of text are stored as single
394 :class:`Text` instances. This simplifies processing text from a DOM tree for
395 many applications.
396
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398.. method:: Node.cloneNode(deep)
399
400 Clone this node. Setting *deep* means to clone all child nodes as well. This
401 returns the clone.
402
403
404.. _dom-nodelist-objects:
405
406NodeList Objects
407^^^^^^^^^^^^^^^^
408
409A :class:`NodeList` represents a sequence of nodes. These objects are used in
410two ways in the DOM Core recommendation: the :class:`Element` objects provides
411one as its list of child nodes, and the :meth:`getElementsByTagName` and
412:meth:`getElementsByTagNameNS` methods of :class:`Node` return objects with this
413interface to represent query results.
414
415The DOM Level 2 recommendation defines one method and one attribute for these
416objects:
417
418
419.. method:: NodeList.item(i)
420
421 Return the *i*'th item from the sequence, if there is one, or ``None``. The
422 index *i* is not allowed to be less then zero or greater than or equal to the
423 length of the sequence.
424
425
426.. attribute:: NodeList.length
427
428 The number of nodes in the sequence.
429
430In addition, the Python DOM interface requires that some additional support is
431provided to allow :class:`NodeList` objects to be used as Python sequences. All
432:class:`NodeList` implementations must include support for :meth:`__len__` and
433:meth:`__getitem__`; this allows iteration over the :class:`NodeList` in
434:keyword:`for` statements and proper support for the :func:`len` built-in
435function.
436
437If a DOM implementation supports modification of the document, the
438:class:`NodeList` implementation must also support the :meth:`__setitem__` and
439:meth:`__delitem__` methods.
440
441
442.. _dom-documenttype-objects:
443
444DocumentType Objects
445^^^^^^^^^^^^^^^^^^^^
446
447Information about the notations and entities declared by a document (including
448the external subset if the parser uses it and can provide the information) is
449available from a :class:`DocumentType` object. The :class:`DocumentType` for a
450document is available from the :class:`Document` object's :attr:`doctype`
451attribute; if there is no ``DOCTYPE`` declaration for the document, the
452document's :attr:`doctype` attribute will be set to ``None`` instead of an
453instance of this interface.
454
455:class:`DocumentType` is a specialization of :class:`Node`, and adds the
456following attributes:
457
458
459.. attribute:: DocumentType.publicId
460
461 The public identifier for the external subset of the document type definition.
462 This will be a string or ``None``.
463
464
465.. attribute:: DocumentType.systemId
466
467 The system identifier for the external subset of the document type definition.
468 This will be a URI as a string, or ``None``.
469
470
471.. attribute:: DocumentType.internalSubset
472
473 A string giving the complete internal subset from the document. This does not
474 include the brackets which enclose the subset. If the document has no internal
475 subset, this should be ``None``.
476
477
478.. attribute:: DocumentType.name
479
480 The name of the root element as given in the ``DOCTYPE`` declaration, if
481 present.
482
483
484.. attribute:: DocumentType.entities
485
486 This is a :class:`NamedNodeMap` giving the definitions of external entities.
487 For entity names defined more than once, only the first definition is provided
488 (others are ignored as required by the XML recommendation). This may be
489 ``None`` if the information is not provided by the parser, or if no entities are
490 defined.
491
492
493.. attribute:: DocumentType.notations
494
495 This is a :class:`NamedNodeMap` giving the definitions of notations. For
496 notation names defined more than once, only the first definition is provided
497 (others are ignored as required by the XML recommendation). This may be
498 ``None`` if the information is not provided by the parser, or if no notations
499 are defined.
500
501
502.. _dom-document-objects:
503
504Document Objects
505^^^^^^^^^^^^^^^^
506
507A :class:`Document` represents an entire XML document, including its constituent
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000508elements, attributes, processing instructions, comments etc. Remember that it
Georg Brandl116aa622007-08-15 14:28:22 +0000509inherits properties from :class:`Node`.
510
511
512.. attribute:: Document.documentElement
513
514 The one and only root element of the document.
515
516
517.. method:: Document.createElement(tagName)
518
519 Create and return a new element node. The element is not inserted into the
520 document when it is created. You need to explicitly insert it with one of the
521 other methods such as :meth:`insertBefore` or :meth:`appendChild`.
522
523
524.. method:: Document.createElementNS(namespaceURI, tagName)
525
526 Create and return a new element with a namespace. The *tagName* may have a
527 prefix. The element is not inserted into the document when it is created. You
528 need to explicitly insert it with one of the other methods such as
529 :meth:`insertBefore` or :meth:`appendChild`.
530
531
532.. method:: Document.createTextNode(data)
533
534 Create and return a text node containing the data passed as a parameter. As
535 with the other creation methods, this one does not insert the node into the
536 tree.
537
538
539.. method:: Document.createComment(data)
540
541 Create and return a comment node containing the data passed as a parameter. As
542 with the other creation methods, this one does not insert the node into the
543 tree.
544
545
546.. method:: Document.createProcessingInstruction(target, data)
547
548 Create and return a processing instruction node containing the *target* and
549 *data* passed as parameters. As with the other creation methods, this one does
550 not insert the node into the tree.
551
552
553.. method:: Document.createAttribute(name)
554
555 Create and return an attribute node. This method does not associate the
556 attribute node with any particular element. You must use
557 :meth:`setAttributeNode` on the appropriate :class:`Element` object to use the
558 newly created attribute instance.
559
560
561.. method:: Document.createAttributeNS(namespaceURI, qualifiedName)
562
563 Create and return an attribute node with a namespace. The *tagName* may have a
564 prefix. This method does not associate the attribute node with any particular
565 element. You must use :meth:`setAttributeNode` on the appropriate
566 :class:`Element` object to use the newly created attribute instance.
567
568
569.. method:: Document.getElementsByTagName(tagName)
570
571 Search for all descendants (direct children, children's children, etc.) with a
572 particular element type name.
573
574
575.. method:: Document.getElementsByTagNameNS(namespaceURI, localName)
576
577 Search for all descendants (direct children, children's children, etc.) with a
578 particular namespace URI and localname. The localname is the part of the
579 namespace after the prefix.
580
581
582.. _dom-element-objects:
583
584Element Objects
585^^^^^^^^^^^^^^^
586
587:class:`Element` is a subclass of :class:`Node`, so inherits all the attributes
588of that class.
589
590
591.. attribute:: Element.tagName
592
593 The element type name. In a namespace-using document it may have colons in it.
594 The value is a string.
595
596
597.. method:: Element.getElementsByTagName(tagName)
598
599 Same as equivalent method in the :class:`Document` class.
600
601
Benjamin Petersonf07d0022009-03-21 17:31:58 +0000602.. method:: Element.getElementsByTagNameNS(namespaceURI, localName)
Georg Brandl116aa622007-08-15 14:28:22 +0000603
604 Same as equivalent method in the :class:`Document` class.
605
606
607.. method:: Element.hasAttribute(name)
608
609 Returns true if the element has an attribute named by *name*.
610
611
612.. method:: Element.hasAttributeNS(namespaceURI, localName)
613
614 Returns true if the element has an attribute named by *namespaceURI* and
615 *localName*.
616
617
618.. method:: Element.getAttribute(name)
619
620 Return the value of the attribute named by *name* as a string. If no such
621 attribute exists, an empty string is returned, as if the attribute had no value.
622
623
624.. method:: Element.getAttributeNode(attrname)
625
626 Return the :class:`Attr` node for the attribute named by *attrname*.
627
628
629.. method:: Element.getAttributeNS(namespaceURI, localName)
630
631 Return the value of the attribute named by *namespaceURI* and *localName* as a
632 string. If no such attribute exists, an empty string is returned, as if the
633 attribute had no value.
634
635
636.. method:: Element.getAttributeNodeNS(namespaceURI, localName)
637
638 Return an attribute value as a node, given a *namespaceURI* and *localName*.
639
640
641.. method:: Element.removeAttribute(name)
642
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000643 Remove an attribute by name. If there is no matching attribute, a
644 :exc:`NotFoundErr` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000645
646
647.. method:: Element.removeAttributeNode(oldAttr)
648
649 Remove and return *oldAttr* from the attribute list, if present. If *oldAttr* is
650 not present, :exc:`NotFoundErr` is raised.
651
652
653.. method:: Element.removeAttributeNS(namespaceURI, localName)
654
655 Remove an attribute by name. Note that it uses a localName, not a qname. No
656 exception is raised if there is no matching attribute.
657
658
659.. method:: Element.setAttribute(name, value)
660
661 Set an attribute value from a string.
662
663
664.. method:: Element.setAttributeNode(newAttr)
665
666 Add a new attribute node to the element, replacing an existing attribute if
667 necessary if the :attr:`name` attribute matches. If a replacement occurs, the
668 old attribute node will be returned. If *newAttr* is already in use,
669 :exc:`InuseAttributeErr` will be raised.
670
671
672.. method:: Element.setAttributeNodeNS(newAttr)
673
674 Add a new attribute node to the element, replacing an existing attribute if
675 necessary if the :attr:`namespaceURI` and :attr:`localName` attributes match.
676 If a replacement occurs, the old attribute node will be returned. If *newAttr*
677 is already in use, :exc:`InuseAttributeErr` will be raised.
678
679
680.. method:: Element.setAttributeNS(namespaceURI, qname, value)
681
682 Set an attribute value from a string, given a *namespaceURI* and a *qname*.
683 Note that a qname is the whole attribute name. This is different than above.
684
685
686.. _dom-attr-objects:
687
688Attr Objects
689^^^^^^^^^^^^
690
691:class:`Attr` inherits from :class:`Node`, so inherits all its attributes.
692
693
694.. attribute:: Attr.name
695
696 The attribute name. In a namespace-using document it may have colons in it.
697
698
699.. attribute:: Attr.localName
700
701 The part of the name following the colon if there is one, else the entire name.
702 This is a read-only attribute.
703
704
705.. attribute:: Attr.prefix
706
707 The part of the name preceding the colon if there is one, else the empty string.
708
709
710.. _dom-attributelist-objects:
711
712NamedNodeMap Objects
713^^^^^^^^^^^^^^^^^^^^
714
715:class:`NamedNodeMap` does *not* inherit from :class:`Node`.
716
717
718.. attribute:: NamedNodeMap.length
719
720 The length of the attribute list.
721
722
723.. method:: NamedNodeMap.item(index)
724
725 Return an attribute with a particular index. The order you get the attributes
726 in is arbitrary but will be consistent for the life of a DOM. Each item is an
727 attribute node. Get its value with the :attr:`value` attribute.
728
729There are also experimental methods that give this class more mapping behavior.
730You can use them or you can use the standardized :meth:`getAttribute\*` family
731of methods on the :class:`Element` objects.
732
733
734.. _dom-comment-objects:
735
736Comment Objects
737^^^^^^^^^^^^^^^
738
739:class:`Comment` represents a comment in the XML document. It is a subclass of
740:class:`Node`, but cannot have child nodes.
741
742
743.. attribute:: Comment.data
744
745 The content of the comment as a string. The attribute contains all characters
746 between the leading ``<!-``\ ``-`` and trailing ``-``\ ``->``, but does not
747 include them.
748
749
750.. _dom-text-objects:
751
752Text and CDATASection Objects
753^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
754
755The :class:`Text` interface represents text in the XML document. If the parser
756and DOM implementation support the DOM's XML extension, portions of the text
757enclosed in CDATA marked sections are stored in :class:`CDATASection` objects.
758These two interfaces are identical, but provide different values for the
759:attr:`nodeType` attribute.
760
761These interfaces extend the :class:`Node` interface. They cannot have child
762nodes.
763
764
765.. attribute:: Text.data
766
767 The content of the text node as a string.
768
769.. note::
770
771 The use of a :class:`CDATASection` node does not indicate that the node
772 represents a complete CDATA marked section, only that the content of the node
773 was part of a CDATA section. A single CDATA section may be represented by more
774 than one node in the document tree. There is no way to determine whether two
775 adjacent :class:`CDATASection` nodes represent different CDATA marked sections.
776
777
778.. _dom-pi-objects:
779
780ProcessingInstruction Objects
781^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
782
783Represents a processing instruction in the XML document; this inherits from the
784:class:`Node` interface and cannot have child nodes.
785
786
787.. attribute:: ProcessingInstruction.target
788
789 The content of the processing instruction up to the first whitespace character.
790 This is a read-only attribute.
791
792
793.. attribute:: ProcessingInstruction.data
794
795 The content of the processing instruction following the first whitespace
796 character.
797
798
799.. _dom-exceptions:
800
801Exceptions
802^^^^^^^^^^
803
Georg Brandl116aa622007-08-15 14:28:22 +0000804The DOM Level 2 recommendation defines a single exception, :exc:`DOMException`,
805and a number of constants that allow applications to determine what sort of
806error occurred. :exc:`DOMException` instances carry a :attr:`code` attribute
807that provides the appropriate value for the specific exception.
808
809The Python DOM interface provides the constants, but also expands the set of
810exceptions so that a specific exception exists for each of the exception codes
811defined by the DOM. The implementations must raise the appropriate specific
812exception, each of which carries the appropriate value for the :attr:`code`
813attribute.
814
815
816.. exception:: DOMException
817
818 Base exception class used for all specific DOM exceptions. This exception class
819 cannot be directly instantiated.
820
821
822.. exception:: DomstringSizeErr
823
824 Raised when a specified range of text does not fit into a string. This is not
825 known to be used in the Python DOM implementations, but may be received from DOM
826 implementations not written in Python.
827
828
829.. exception:: HierarchyRequestErr
830
831 Raised when an attempt is made to insert a node where the node type is not
832 allowed.
833
834
835.. exception:: IndexSizeErr
836
837 Raised when an index or size parameter to a method is negative or exceeds the
838 allowed values.
839
840
841.. exception:: InuseAttributeErr
842
843 Raised when an attempt is made to insert an :class:`Attr` node that is already
844 present elsewhere in the document.
845
846
847.. exception:: InvalidAccessErr
848
849 Raised if a parameter or an operation is not supported on the underlying object.
850
851
852.. exception:: InvalidCharacterErr
853
854 This exception is raised when a string parameter contains a character that is
855 not permitted in the context it's being used in by the XML 1.0 recommendation.
856 For example, attempting to create an :class:`Element` node with a space in the
857 element type name will cause this error to be raised.
858
859
860.. exception:: InvalidModificationErr
861
862 Raised when an attempt is made to modify the type of a node.
863
864
865.. exception:: InvalidStateErr
866
867 Raised when an attempt is made to use an object that is not defined or is no
868 longer usable.
869
870
871.. exception:: NamespaceErr
872
873 If an attempt is made to change any object in a way that is not permitted with
874 regard to the `Namespaces in XML <http://www.w3.org/TR/REC-xml-names/>`_
875 recommendation, this exception is raised.
876
877
878.. exception:: NotFoundErr
879
880 Exception when a node does not exist in the referenced context. For example,
881 :meth:`NamedNodeMap.removeNamedItem` will raise this if the node passed in does
882 not exist in the map.
883
884
885.. exception:: NotSupportedErr
886
887 Raised when the implementation does not support the requested type of object or
888 operation.
889
890
891.. exception:: NoDataAllowedErr
892
893 This is raised if data is specified for a node which does not support data.
894
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000895 .. XXX a better explanation is needed!
Georg Brandl116aa622007-08-15 14:28:22 +0000896
897
898.. exception:: NoModificationAllowedErr
899
900 Raised on attempts to modify an object where modifications are not allowed (such
901 as for read-only nodes).
902
903
904.. exception:: SyntaxErr
905
906 Raised when an invalid or illegal string is specified.
907
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000908 .. XXX how is this different from InvalidCharacterErr?
Georg Brandl116aa622007-08-15 14:28:22 +0000909
910
911.. exception:: WrongDocumentErr
912
913 Raised when a node is inserted in a different document than it currently belongs
914 to, and the implementation does not support migrating the node from one document
915 to the other.
916
917The exception codes defined in the DOM recommendation map to the exceptions
918described above according to this table:
919
920+--------------------------------------+---------------------------------+
921| Constant | Exception |
922+======================================+=================================+
923| :const:`DOMSTRING_SIZE_ERR` | :exc:`DomstringSizeErr` |
924+--------------------------------------+---------------------------------+
925| :const:`HIERARCHY_REQUEST_ERR` | :exc:`HierarchyRequestErr` |
926+--------------------------------------+---------------------------------+
927| :const:`INDEX_SIZE_ERR` | :exc:`IndexSizeErr` |
928+--------------------------------------+---------------------------------+
929| :const:`INUSE_ATTRIBUTE_ERR` | :exc:`InuseAttributeErr` |
930+--------------------------------------+---------------------------------+
931| :const:`INVALID_ACCESS_ERR` | :exc:`InvalidAccessErr` |
932+--------------------------------------+---------------------------------+
933| :const:`INVALID_CHARACTER_ERR` | :exc:`InvalidCharacterErr` |
934+--------------------------------------+---------------------------------+
935| :const:`INVALID_MODIFICATION_ERR` | :exc:`InvalidModificationErr` |
936+--------------------------------------+---------------------------------+
937| :const:`INVALID_STATE_ERR` | :exc:`InvalidStateErr` |
938+--------------------------------------+---------------------------------+
939| :const:`NAMESPACE_ERR` | :exc:`NamespaceErr` |
940+--------------------------------------+---------------------------------+
941| :const:`NOT_FOUND_ERR` | :exc:`NotFoundErr` |
942+--------------------------------------+---------------------------------+
943| :const:`NOT_SUPPORTED_ERR` | :exc:`NotSupportedErr` |
944+--------------------------------------+---------------------------------+
945| :const:`NO_DATA_ALLOWED_ERR` | :exc:`NoDataAllowedErr` |
946+--------------------------------------+---------------------------------+
947| :const:`NO_MODIFICATION_ALLOWED_ERR` | :exc:`NoModificationAllowedErr` |
948+--------------------------------------+---------------------------------+
949| :const:`SYNTAX_ERR` | :exc:`SyntaxErr` |
950+--------------------------------------+---------------------------------+
951| :const:`WRONG_DOCUMENT_ERR` | :exc:`WrongDocumentErr` |
952+--------------------------------------+---------------------------------+
953
954
955.. _dom-conformance:
956
957Conformance
958-----------
959
960This section describes the conformance requirements and relationships between
961the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for
962Python.
963
964
965.. _dom-type-mapping:
966
967Type Mapping
968^^^^^^^^^^^^
969
970The primitive IDL types used in the DOM specification are mapped to Python types
971according to the following table.
972
973+------------------+-------------------------------------------+
974| IDL Type | Python Type |
975+==================+===========================================+
976| ``boolean`` | ``IntegerType`` (with a value of ``0`` or |
977| | ``1``) |
978+------------------+-------------------------------------------+
979| ``int`` | ``IntegerType`` |
980+------------------+-------------------------------------------+
981| ``long int`` | ``IntegerType`` |
982+------------------+-------------------------------------------+
983| ``unsigned int`` | ``IntegerType`` |
984+------------------+-------------------------------------------+
985
986Additionally, the :class:`DOMString` defined in the recommendation is mapped to
Georg Brandlf6945182008-02-01 11:56:49 +0000987a bytes or string object. Applications should be able to handle
Georg Brandl116aa622007-08-15 14:28:22 +0000988Unicode whenever a string is returned from the DOM.
989
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000990The IDL ``null`` value is mapped to ``None``, which may be accepted or
991provided by the implementation whenever ``null`` is allowed by the API.
Georg Brandl116aa622007-08-15 14:28:22 +0000992
993
994.. _dom-accessor-methods:
995
996Accessor Methods
997^^^^^^^^^^^^^^^^
998
999The mapping from OMG IDL to Python defines accessor functions for IDL
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001000``attribute`` declarations in much the way the Java mapping does.
Georg Brandl116aa622007-08-15 14:28:22 +00001001Mapping the IDL declarations ::
1002
1003 readonly attribute string someValue;
1004 attribute string anotherValue;
1005
1006yields three accessor functions: a "get" method for :attr:`someValue`
1007(:meth:`_get_someValue`), and "get" and "set" methods for :attr:`anotherValue`
1008(:meth:`_get_anotherValue` and :meth:`_set_anotherValue`). The mapping, in
1009particular, does not require that the IDL attributes are accessible as normal
1010Python attributes: ``object.someValue`` is *not* required to work, and may
1011raise an :exc:`AttributeError`.
1012
1013The Python DOM API, however, *does* require that normal attribute access work.
1014This means that the typical surrogates generated by Python IDL compilers are not
1015likely to work, and wrapper objects may be needed on the client if the DOM
1016objects are accessed via CORBA. While this does require some additional
1017consideration for CORBA DOM clients, the implementers with experience using DOM
1018over CORBA from Python do not consider this a problem. Attributes that are
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001019declared ``readonly`` may not restrict write access in all DOM
Georg Brandl116aa622007-08-15 14:28:22 +00001020implementations.
1021
1022In the Python DOM API, accessor functions are not required. If provided, they
1023should take the form defined by the Python IDL mapping, but these methods are
1024considered unnecessary since the attributes are accessible directly from Python.
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001025"Set" accessors should never be provided for ``readonly`` attributes.
Georg Brandl116aa622007-08-15 14:28:22 +00001026
1027The IDL definitions do not fully embody the requirements of the W3C DOM API,
1028such as the notion of certain objects, such as the return value of
1029:meth:`getElementsByTagName`, being "live". The Python DOM API does not require
1030implementations to enforce such requirements.
1031