blob: c1786a63068561f643d106bb74f4d16a20cef47f [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 Peterson20211002009-11-25 18:34:42 +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 Brandl7f01a132009-09-16 15:58:14 +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
Fred Drakeade19172010-05-12 02:34:50 +0000696 The attribute name.
697 In a namespace-using document it may include a colon.
Georg Brandl116aa622007-08-15 14:28:22 +0000698
699
700.. attribute:: Attr.localName
701
Fred Drakeade19172010-05-12 02:34:50 +0000702 The part of the name following the colon if there is one, else the
703 entire name.
Georg Brandl116aa622007-08-15 14:28:22 +0000704 This is a read-only attribute.
705
706
707.. attribute:: Attr.prefix
708
Fred Drakeade19172010-05-12 02:34:50 +0000709 The part of the name preceding the colon if there is one, else the
710 empty string.
711
712
713.. attribute:: Attr.value
714
715 The text value of the attribute. This is a synonym for the
716 :attr:`nodeValue` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718
719.. _dom-attributelist-objects:
720
721NamedNodeMap Objects
722^^^^^^^^^^^^^^^^^^^^
723
724:class:`NamedNodeMap` does *not* inherit from :class:`Node`.
725
726
727.. attribute:: NamedNodeMap.length
728
729 The length of the attribute list.
730
731
732.. method:: NamedNodeMap.item(index)
733
734 Return an attribute with a particular index. The order you get the attributes
735 in is arbitrary but will be consistent for the life of a DOM. Each item is an
736 attribute node. Get its value with the :attr:`value` attribute.
737
738There are also experimental methods that give this class more mapping behavior.
739You can use them or you can use the standardized :meth:`getAttribute\*` family
740of methods on the :class:`Element` objects.
741
742
743.. _dom-comment-objects:
744
745Comment Objects
746^^^^^^^^^^^^^^^
747
748:class:`Comment` represents a comment in the XML document. It is a subclass of
749:class:`Node`, but cannot have child nodes.
750
751
752.. attribute:: Comment.data
753
754 The content of the comment as a string. The attribute contains all characters
755 between the leading ``<!-``\ ``-`` and trailing ``-``\ ``->``, but does not
756 include them.
757
758
759.. _dom-text-objects:
760
761Text and CDATASection Objects
762^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
763
764The :class:`Text` interface represents text in the XML document. If the parser
765and DOM implementation support the DOM's XML extension, portions of the text
766enclosed in CDATA marked sections are stored in :class:`CDATASection` objects.
767These two interfaces are identical, but provide different values for the
768:attr:`nodeType` attribute.
769
770These interfaces extend the :class:`Node` interface. They cannot have child
771nodes.
772
773
774.. attribute:: Text.data
775
776 The content of the text node as a string.
777
778.. note::
779
780 The use of a :class:`CDATASection` node does not indicate that the node
781 represents a complete CDATA marked section, only that the content of the node
782 was part of a CDATA section. A single CDATA section may be represented by more
783 than one node in the document tree. There is no way to determine whether two
784 adjacent :class:`CDATASection` nodes represent different CDATA marked sections.
785
786
787.. _dom-pi-objects:
788
789ProcessingInstruction Objects
790^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
791
792Represents a processing instruction in the XML document; this inherits from the
793:class:`Node` interface and cannot have child nodes.
794
795
796.. attribute:: ProcessingInstruction.target
797
798 The content of the processing instruction up to the first whitespace character.
799 This is a read-only attribute.
800
801
802.. attribute:: ProcessingInstruction.data
803
804 The content of the processing instruction following the first whitespace
805 character.
806
807
808.. _dom-exceptions:
809
810Exceptions
811^^^^^^^^^^
812
Georg Brandl116aa622007-08-15 14:28:22 +0000813The DOM Level 2 recommendation defines a single exception, :exc:`DOMException`,
814and a number of constants that allow applications to determine what sort of
815error occurred. :exc:`DOMException` instances carry a :attr:`code` attribute
816that provides the appropriate value for the specific exception.
817
818The Python DOM interface provides the constants, but also expands the set of
819exceptions so that a specific exception exists for each of the exception codes
820defined by the DOM. The implementations must raise the appropriate specific
821exception, each of which carries the appropriate value for the :attr:`code`
822attribute.
823
824
825.. exception:: DOMException
826
827 Base exception class used for all specific DOM exceptions. This exception class
828 cannot be directly instantiated.
829
830
831.. exception:: DomstringSizeErr
832
833 Raised when a specified range of text does not fit into a string. This is not
834 known to be used in the Python DOM implementations, but may be received from DOM
835 implementations not written in Python.
836
837
838.. exception:: HierarchyRequestErr
839
840 Raised when an attempt is made to insert a node where the node type is not
841 allowed.
842
843
844.. exception:: IndexSizeErr
845
846 Raised when an index or size parameter to a method is negative or exceeds the
847 allowed values.
848
849
850.. exception:: InuseAttributeErr
851
852 Raised when an attempt is made to insert an :class:`Attr` node that is already
853 present elsewhere in the document.
854
855
856.. exception:: InvalidAccessErr
857
858 Raised if a parameter or an operation is not supported on the underlying object.
859
860
861.. exception:: InvalidCharacterErr
862
863 This exception is raised when a string parameter contains a character that is
864 not permitted in the context it's being used in by the XML 1.0 recommendation.
865 For example, attempting to create an :class:`Element` node with a space in the
866 element type name will cause this error to be raised.
867
868
869.. exception:: InvalidModificationErr
870
871 Raised when an attempt is made to modify the type of a node.
872
873
874.. exception:: InvalidStateErr
875
876 Raised when an attempt is made to use an object that is not defined or is no
877 longer usable.
878
879
880.. exception:: NamespaceErr
881
882 If an attempt is made to change any object in a way that is not permitted with
883 regard to the `Namespaces in XML <http://www.w3.org/TR/REC-xml-names/>`_
884 recommendation, this exception is raised.
885
886
887.. exception:: NotFoundErr
888
889 Exception when a node does not exist in the referenced context. For example,
890 :meth:`NamedNodeMap.removeNamedItem` will raise this if the node passed in does
891 not exist in the map.
892
893
894.. exception:: NotSupportedErr
895
896 Raised when the implementation does not support the requested type of object or
897 operation.
898
899
900.. exception:: NoDataAllowedErr
901
902 This is raised if data is specified for a node which does not support data.
903
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000904 .. XXX a better explanation is needed!
Georg Brandl116aa622007-08-15 14:28:22 +0000905
906
907.. exception:: NoModificationAllowedErr
908
909 Raised on attempts to modify an object where modifications are not allowed (such
910 as for read-only nodes).
911
912
913.. exception:: SyntaxErr
914
915 Raised when an invalid or illegal string is specified.
916
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000917 .. XXX how is this different from InvalidCharacterErr?
Georg Brandl116aa622007-08-15 14:28:22 +0000918
919
920.. exception:: WrongDocumentErr
921
922 Raised when a node is inserted in a different document than it currently belongs
923 to, and the implementation does not support migrating the node from one document
924 to the other.
925
926The exception codes defined in the DOM recommendation map to the exceptions
927described above according to this table:
928
929+--------------------------------------+---------------------------------+
930| Constant | Exception |
931+======================================+=================================+
932| :const:`DOMSTRING_SIZE_ERR` | :exc:`DomstringSizeErr` |
933+--------------------------------------+---------------------------------+
934| :const:`HIERARCHY_REQUEST_ERR` | :exc:`HierarchyRequestErr` |
935+--------------------------------------+---------------------------------+
936| :const:`INDEX_SIZE_ERR` | :exc:`IndexSizeErr` |
937+--------------------------------------+---------------------------------+
938| :const:`INUSE_ATTRIBUTE_ERR` | :exc:`InuseAttributeErr` |
939+--------------------------------------+---------------------------------+
940| :const:`INVALID_ACCESS_ERR` | :exc:`InvalidAccessErr` |
941+--------------------------------------+---------------------------------+
942| :const:`INVALID_CHARACTER_ERR` | :exc:`InvalidCharacterErr` |
943+--------------------------------------+---------------------------------+
944| :const:`INVALID_MODIFICATION_ERR` | :exc:`InvalidModificationErr` |
945+--------------------------------------+---------------------------------+
946| :const:`INVALID_STATE_ERR` | :exc:`InvalidStateErr` |
947+--------------------------------------+---------------------------------+
948| :const:`NAMESPACE_ERR` | :exc:`NamespaceErr` |
949+--------------------------------------+---------------------------------+
950| :const:`NOT_FOUND_ERR` | :exc:`NotFoundErr` |
951+--------------------------------------+---------------------------------+
952| :const:`NOT_SUPPORTED_ERR` | :exc:`NotSupportedErr` |
953+--------------------------------------+---------------------------------+
954| :const:`NO_DATA_ALLOWED_ERR` | :exc:`NoDataAllowedErr` |
955+--------------------------------------+---------------------------------+
956| :const:`NO_MODIFICATION_ALLOWED_ERR` | :exc:`NoModificationAllowedErr` |
957+--------------------------------------+---------------------------------+
958| :const:`SYNTAX_ERR` | :exc:`SyntaxErr` |
959+--------------------------------------+---------------------------------+
960| :const:`WRONG_DOCUMENT_ERR` | :exc:`WrongDocumentErr` |
961+--------------------------------------+---------------------------------+
962
963
964.. _dom-conformance:
965
966Conformance
967-----------
968
969This section describes the conformance requirements and relationships between
970the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for
971Python.
972
973
974.. _dom-type-mapping:
975
976Type Mapping
977^^^^^^^^^^^^
978
Andrew M. Kuchling4d4d1ce2010-07-25 22:57:12 +0000979The IDL types used in the DOM specification are mapped to Python types
Georg Brandl116aa622007-08-15 14:28:22 +0000980according to the following table.
981
982+------------------+-------------------------------------------+
983| IDL Type | Python Type |
984+==================+===========================================+
Andrew M. Kuchling4d4d1ce2010-07-25 22:57:12 +0000985| ``boolean`` | ``bool`` or ``int`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000986+------------------+-------------------------------------------+
Andrew M. Kuchling4d4d1ce2010-07-25 22:57:12 +0000987| ``int`` | ``int`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000988+------------------+-------------------------------------------+
Andrew M. Kuchling4d4d1ce2010-07-25 22:57:12 +0000989| ``long int`` | ``int`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000990+------------------+-------------------------------------------+
Andrew M. Kuchling4d4d1ce2010-07-25 22:57:12 +0000991| ``unsigned int`` | ``int`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000992+------------------+-------------------------------------------+
Andrew M. Kuchling4d4d1ce2010-07-25 22:57:12 +0000993| ``DOMString`` | ``str`` or ``bytes`` |
994+------------------+-------------------------------------------+
995| ``null`` | ``None`` |
996+------------------+-------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000997
998.. _dom-accessor-methods:
999
1000Accessor Methods
1001^^^^^^^^^^^^^^^^
1002
1003The mapping from OMG IDL to Python defines accessor functions for IDL
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001004``attribute`` declarations in much the way the Java mapping does.
Georg Brandl116aa622007-08-15 14:28:22 +00001005Mapping the IDL declarations ::
1006
1007 readonly attribute string someValue;
1008 attribute string anotherValue;
1009
1010yields three accessor functions: a "get" method for :attr:`someValue`
1011(:meth:`_get_someValue`), and "get" and "set" methods for :attr:`anotherValue`
1012(:meth:`_get_anotherValue` and :meth:`_set_anotherValue`). The mapping, in
1013particular, does not require that the IDL attributes are accessible as normal
1014Python attributes: ``object.someValue`` is *not* required to work, and may
1015raise an :exc:`AttributeError`.
1016
1017The Python DOM API, however, *does* require that normal attribute access work.
1018This means that the typical surrogates generated by Python IDL compilers are not
1019likely to work, and wrapper objects may be needed on the client if the DOM
1020objects are accessed via CORBA. While this does require some additional
1021consideration for CORBA DOM clients, the implementers with experience using DOM
1022over CORBA from Python do not consider this a problem. Attributes that are
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001023declared ``readonly`` may not restrict write access in all DOM
Georg Brandl116aa622007-08-15 14:28:22 +00001024implementations.
1025
1026In the Python DOM API, accessor functions are not required. If provided, they
1027should take the form defined by the Python IDL mapping, but these methods are
1028considered unnecessary since the attributes are accessible directly from Python.
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001029"Set" accessors should never be provided for ``readonly`` attributes.
Georg Brandl116aa622007-08-15 14:28:22 +00001030
1031The IDL definitions do not fully embody the requirements of the W3C DOM API,
1032such as the notion of certain objects, such as the return value of
1033:meth:`getElementsByTagName`, being "live". The Python DOM API does not require
1034implementations to enforce such requirements.
1035