doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
wsgiref.validate.validator(application)
Wrap application and return a new WSGI application object. The returned application will forward all requests to the original application, and will check that both the application and the server invoking it are conforming to the WSGI specification and to RFC 2616. Any detected nonconformance results in an AssertionError being raised; note, however, that how these errors are handled is server-dependent. For example, wsgiref.simple_server and other servers based on wsgiref.handlers (that don’t override the error handling methods to do something else) will simply output a message that an error has occurred, and dump the traceback to sys.stderr or some other error stream. This wrapper may also generate output using the warnings module to indicate behaviors that are questionable but which may not actually be prohibited by PEP 3333. Unless they are suppressed using Python command-line options or the warnings API, any such warnings will be written to sys.stderr (not wsgi.errors, unless they happen to be the same object). Example usage: from wsgiref.validate import validator
from wsgiref.simple_server import make_server
# Our callable object which is intentionally not compliant to the
# standard, so the validator is going to break
def simple_app(environ, start_response):
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/plain')] # HTTP Headers
start_response(status, headers)
# This is going to break because we need to return a list, and
# the validator is going to inform us
return b"Hello World"
# This is the application wrapped in a validator
validator_app = validator(simple_app)
with make_server('', 8000, validator_app) as httpd:
print("Listening on port 8000....")
httpd.serve_forever() | python.library.wsgiref#wsgiref.validate.validator |
xdrlib — Encode and decode XDR data Source code: Lib/xdrlib.py The xdrlib module supports the External Data Representation Standard as described in RFC 1014, written by Sun Microsystems, Inc. June 1987. It supports most of the data types described in the RFC. The xdrlib module defines two classes, one for packing variables into XDR representation, and another for unpacking from XDR representation. There are also two exception classes.
class xdrlib.Packer
Packer is the class for packing data into XDR representation. The Packer class is instantiated with no arguments.
class xdrlib.Unpacker(data)
Unpacker is the complementary class which unpacks XDR data values from a string buffer. The input buffer is given as data.
See also
RFC 1014 - XDR: External Data Representation Standard
This RFC defined the encoding of data which was XDR at the time this module was originally written. It has apparently been obsoleted by RFC 1832.
RFC 1832 - XDR: External Data Representation Standard
Newer RFC that provides a revised definition of XDR. Packer Objects Packer instances have the following methods:
Packer.get_buffer()
Returns the current pack buffer as a string.
Packer.reset()
Resets the pack buffer to the empty string.
In general, you can pack any of the most common XDR data types by calling the appropriate pack_type() method. Each method takes a single argument, the value to pack. The following simple data type packing methods are supported: pack_uint(), pack_int(), pack_enum(), pack_bool(), pack_uhyper(), and pack_hyper().
Packer.pack_float(value)
Packs the single-precision floating point number value.
Packer.pack_double(value)
Packs the double-precision floating point number value.
The following methods support packing strings, bytes, and opaque data:
Packer.pack_fstring(n, s)
Packs a fixed length string, s. n is the length of the string but it is not packed into the data buffer. The string is padded with null bytes if necessary to guaranteed 4 byte alignment.
Packer.pack_fopaque(n, data)
Packs a fixed length opaque data stream, similarly to pack_fstring().
Packer.pack_string(s)
Packs a variable length string, s. The length of the string is first packed as an unsigned integer, then the string data is packed with pack_fstring().
Packer.pack_opaque(data)
Packs a variable length opaque data string, similarly to pack_string().
Packer.pack_bytes(bytes)
Packs a variable length byte stream, similarly to pack_string().
The following methods support packing arrays and lists:
Packer.pack_list(list, pack_item)
Packs a list of homogeneous items. This method is useful for lists with an indeterminate size; i.e. the size is not available until the entire list has been walked. For each item in the list, an unsigned integer 1 is packed first, followed by the data value from the list. pack_item is the function that is called to pack the individual item. At the end of the list, an unsigned integer 0 is packed. For example, to pack a list of integers, the code might appear like this: import xdrlib
p = xdrlib.Packer()
p.pack_list([1, 2, 3], p.pack_int)
Packer.pack_farray(n, array, pack_item)
Packs a fixed length list (array) of homogeneous items. n is the length of the list; it is not packed into the buffer, but a ValueError exception is raised if len(array) is not equal to n. As above, pack_item is the function used to pack each element.
Packer.pack_array(list, pack_item)
Packs a variable length list of homogeneous items. First, the length of the list is packed as an unsigned integer, then each element is packed as in pack_farray() above.
Unpacker Objects The Unpacker class offers the following methods:
Unpacker.reset(data)
Resets the string buffer with the given data.
Unpacker.get_position()
Returns the current unpack position in the data buffer.
Unpacker.set_position(position)
Sets the data buffer unpack position to position. You should be careful about using get_position() and set_position().
Unpacker.get_buffer()
Returns the current unpack data buffer as a string.
Unpacker.done()
Indicates unpack completion. Raises an Error exception if all of the data has not been unpacked.
In addition, every data type that can be packed with a Packer, can be unpacked with an Unpacker. Unpacking methods are of the form unpack_type(), and take no arguments. They return the unpacked object.
Unpacker.unpack_float()
Unpacks a single-precision floating point number.
Unpacker.unpack_double()
Unpacks a double-precision floating point number, similarly to unpack_float().
In addition, the following methods unpack strings, bytes, and opaque data:
Unpacker.unpack_fstring(n)
Unpacks and returns a fixed length string. n is the number of characters expected. Padding with null bytes to guaranteed 4 byte alignment is assumed.
Unpacker.unpack_fopaque(n)
Unpacks and returns a fixed length opaque data stream, similarly to unpack_fstring().
Unpacker.unpack_string()
Unpacks and returns a variable length string. The length of the string is first unpacked as an unsigned integer, then the string data is unpacked with unpack_fstring().
Unpacker.unpack_opaque()
Unpacks and returns a variable length opaque data string, similarly to unpack_string().
Unpacker.unpack_bytes()
Unpacks and returns a variable length byte stream, similarly to unpack_string().
The following methods support unpacking arrays and lists:
Unpacker.unpack_list(unpack_item)
Unpacks and returns a list of homogeneous items. The list is unpacked one element at a time by first unpacking an unsigned integer flag. If the flag is 1, then the item is unpacked and appended to the list. A flag of 0 indicates the end of the list. unpack_item is the function that is called to unpack the items.
Unpacker.unpack_farray(n, unpack_item)
Unpacks and returns (as a list) a fixed length array of homogeneous items. n is number of list elements to expect in the buffer. As above, unpack_item is the function used to unpack each element.
Unpacker.unpack_array(unpack_item)
Unpacks and returns a variable length list of homogeneous items. First, the length of the list is unpacked as an unsigned integer, then each element is unpacked as in unpack_farray() above.
Exceptions Exceptions in this module are coded as class instances:
exception xdrlib.Error
The base exception class. Error has a single public attribute msg containing the description of the error.
exception xdrlib.ConversionError
Class derived from Error. Contains no additional instance variables.
Here is an example of how you would catch one of these exceptions: import xdrlib
p = xdrlib.Packer()
try:
p.pack_double(8.01)
except xdrlib.ConversionError as instance:
print('packing the double failed:', instance.msg) | python.library.xdrlib |
exception xdrlib.ConversionError
Class derived from Error. Contains no additional instance variables. | python.library.xdrlib#xdrlib.ConversionError |
exception xdrlib.Error
The base exception class. Error has a single public attribute msg containing the description of the error. | python.library.xdrlib#xdrlib.Error |
class xdrlib.Packer
Packer is the class for packing data into XDR representation. The Packer class is instantiated with no arguments. | python.library.xdrlib#xdrlib.Packer |
Packer.get_buffer()
Returns the current pack buffer as a string. | python.library.xdrlib#xdrlib.Packer.get_buffer |
Packer.pack_array(list, pack_item)
Packs a variable length list of homogeneous items. First, the length of the list is packed as an unsigned integer, then each element is packed as in pack_farray() above. | python.library.xdrlib#xdrlib.Packer.pack_array |
Packer.pack_bytes(bytes)
Packs a variable length byte stream, similarly to pack_string(). | python.library.xdrlib#xdrlib.Packer.pack_bytes |
Packer.pack_double(value)
Packs the double-precision floating point number value. | python.library.xdrlib#xdrlib.Packer.pack_double |
Packer.pack_farray(n, array, pack_item)
Packs a fixed length list (array) of homogeneous items. n is the length of the list; it is not packed into the buffer, but a ValueError exception is raised if len(array) is not equal to n. As above, pack_item is the function used to pack each element. | python.library.xdrlib#xdrlib.Packer.pack_farray |
Packer.pack_float(value)
Packs the single-precision floating point number value. | python.library.xdrlib#xdrlib.Packer.pack_float |
Packer.pack_fopaque(n, data)
Packs a fixed length opaque data stream, similarly to pack_fstring(). | python.library.xdrlib#xdrlib.Packer.pack_fopaque |
Packer.pack_fstring(n, s)
Packs a fixed length string, s. n is the length of the string but it is not packed into the data buffer. The string is padded with null bytes if necessary to guaranteed 4 byte alignment. | python.library.xdrlib#xdrlib.Packer.pack_fstring |
Packer.pack_list(list, pack_item)
Packs a list of homogeneous items. This method is useful for lists with an indeterminate size; i.e. the size is not available until the entire list has been walked. For each item in the list, an unsigned integer 1 is packed first, followed by the data value from the list. pack_item is the function that is called to pack the individual item. At the end of the list, an unsigned integer 0 is packed. For example, to pack a list of integers, the code might appear like this: import xdrlib
p = xdrlib.Packer()
p.pack_list([1, 2, 3], p.pack_int) | python.library.xdrlib#xdrlib.Packer.pack_list |
Packer.pack_opaque(data)
Packs a variable length opaque data string, similarly to pack_string(). | python.library.xdrlib#xdrlib.Packer.pack_opaque |
Packer.pack_string(s)
Packs a variable length string, s. The length of the string is first packed as an unsigned integer, then the string data is packed with pack_fstring(). | python.library.xdrlib#xdrlib.Packer.pack_string |
Packer.reset()
Resets the pack buffer to the empty string. | python.library.xdrlib#xdrlib.Packer.reset |
class xdrlib.Unpacker(data)
Unpacker is the complementary class which unpacks XDR data values from a string buffer. The input buffer is given as data. | python.library.xdrlib#xdrlib.Unpacker |
Unpacker.done()
Indicates unpack completion. Raises an Error exception if all of the data has not been unpacked. | python.library.xdrlib#xdrlib.Unpacker.done |
Unpacker.get_buffer()
Returns the current unpack data buffer as a string. | python.library.xdrlib#xdrlib.Unpacker.get_buffer |
Unpacker.get_position()
Returns the current unpack position in the data buffer. | python.library.xdrlib#xdrlib.Unpacker.get_position |
Unpacker.reset(data)
Resets the string buffer with the given data. | python.library.xdrlib#xdrlib.Unpacker.reset |
Unpacker.set_position(position)
Sets the data buffer unpack position to position. You should be careful about using get_position() and set_position(). | python.library.xdrlib#xdrlib.Unpacker.set_position |
Unpacker.unpack_array(unpack_item)
Unpacks and returns a variable length list of homogeneous items. First, the length of the list is unpacked as an unsigned integer, then each element is unpacked as in unpack_farray() above. | python.library.xdrlib#xdrlib.Unpacker.unpack_array |
Unpacker.unpack_bytes()
Unpacks and returns a variable length byte stream, similarly to unpack_string(). | python.library.xdrlib#xdrlib.Unpacker.unpack_bytes |
Unpacker.unpack_double()
Unpacks a double-precision floating point number, similarly to unpack_float(). | python.library.xdrlib#xdrlib.Unpacker.unpack_double |
Unpacker.unpack_farray(n, unpack_item)
Unpacks and returns (as a list) a fixed length array of homogeneous items. n is number of list elements to expect in the buffer. As above, unpack_item is the function used to unpack each element. | python.library.xdrlib#xdrlib.Unpacker.unpack_farray |
Unpacker.unpack_float()
Unpacks a single-precision floating point number. | python.library.xdrlib#xdrlib.Unpacker.unpack_float |
Unpacker.unpack_fopaque(n)
Unpacks and returns a fixed length opaque data stream, similarly to unpack_fstring(). | python.library.xdrlib#xdrlib.Unpacker.unpack_fopaque |
Unpacker.unpack_fstring(n)
Unpacks and returns a fixed length string. n is the number of characters expected. Padding with null bytes to guaranteed 4 byte alignment is assumed. | python.library.xdrlib#xdrlib.Unpacker.unpack_fstring |
Unpacker.unpack_list(unpack_item)
Unpacks and returns a list of homogeneous items. The list is unpacked one element at a time by first unpacking an unsigned integer flag. If the flag is 1, then the item is unpacked and appended to the list. A flag of 0 indicates the end of the list. unpack_item is the function that is called to unpack the items. | python.library.xdrlib#xdrlib.Unpacker.unpack_list |
Unpacker.unpack_opaque()
Unpacks and returns a variable length opaque data string, similarly to unpack_string(). | python.library.xdrlib#xdrlib.Unpacker.unpack_opaque |
Unpacker.unpack_string()
Unpacks and returns a variable length string. The length of the string is first unpacked as an unsigned integer, then the string data is unpacked with unpack_fstring(). | python.library.xdrlib#xdrlib.Unpacker.unpack_string |
xml.dom — The Document Object Model API Source code: Lib/xml/dom/__init__.py The Document Object Model, or “DOM,” is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents. A DOM implementation presents an XML document as a tree structure, or allows client code to build such a structure from scratch. It then gives access to the structure through a set of objects which provided well-known interfaces. The DOM is extremely useful for random-access applications. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another. If you are looking at a text node, you have no access to a containing element. When you write a SAX application, you need to keep track of your program’s position in the document somewhere in your own code. SAX does not do it for you. Also, if you need to look ahead in the XML document, you are just out of luck. Some applications are simply impossible in an event driven model with no access to a tree. Of course you could build some sort of tree yourself in SAX events, but the DOM allows you to avoid writing that code. The DOM is a standard tree representation for XML data. The Document Object Model is being defined by the W3C in stages, or “levels” in their terminology. The Python mapping of the API is substantially based on the DOM Level 2 recommendation. DOM applications typically start by parsing some XML into a DOM. How this is accomplished is not covered at all by DOM Level 1, and Level 2 provides only limited improvements: There is a DOMImplementation object class which provides access to Document creation methods, but no way to access an XML reader/parser/Document builder in an implementation-independent way. There is also no well-defined way to access these methods without an existing Document object. In Python, each DOM implementation will provide a function getDOMImplementation(). DOM Level 3 adds a Load/Store specification, which defines an interface to the reader, but this is not yet available in the Python standard library. Once you have a DOM document object, you can access the parts of your XML document through its properties and methods. These properties are defined in the DOM specification; this portion of the reference manual describes the interpretation of the specification in Python. The specification provided by the W3C defines the DOM API for Java, ECMAScript, and OMG IDL. The Python mapping defined here is based in large part on the IDL version of the specification, but strict compliance is not required (though implementations are free to support the strict mapping from IDL). See section Conformance for a detailed discussion of mapping requirements. See also Document Object Model (DOM) Level 2 Specification
The W3C recommendation upon which the Python DOM API is based. Document Object Model (DOM) Level 1 Specification
The W3C recommendation for the DOM supported by xml.dom.minidom. Python Language Mapping Specification
This specifies the mapping from OMG IDL to Python. Module Contents The xml.dom contains the following functions:
xml.dom.registerDOMImplementation(name, factory)
Register the factory function with the name name. The factory function should return an object which implements the DOMImplementation interface. The factory function can return the same object every time, or a new one for each call, as appropriate for the specific implementation (e.g. if that implementation supports some customization).
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. 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.
Some convenience constants are also provided:
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
The namespace URI associated with the reserved prefix xml, as defined by Namespaces in XML (section 4).
xml.dom.XMLNS_NAMESPACE
The namespace URI for namespace declarations, as defined by Document Object Model (DOM) Level 2 Core Specification (section 1.1.8).
xml.dom.XHTML_NAMESPACE
The URI of the XHTML namespace as defined by XHTML 1.0: The Extensible HyperText Markup Language (section 3.1.1).
In addition, xml.dom contains a base Node class and the DOM exception classes. The Node class provided by this module does not implement any of the methods or attributes defined by the DOM specification; concrete DOM implementations must provide those. The Node class provided as part of this module does provide the constants used for the nodeType attribute on concrete Node objects; they are located within the class rather than at the module level to conform with the DOM specifications. Objects in the DOM The definitive documentation for the DOM is the DOM specification from the W3C. Note that DOM attributes may also be manipulated as nodes instead of as simple strings. It is fairly rare that you must do this, however, so this usage is not yet documented.
Interface Section Purpose
DOMImplementation DOMImplementation Objects Interface to the underlying implementation.
Node Node Objects Base interface for most objects in a document.
NodeList NodeList Objects Interface for a sequence of nodes.
DocumentType DocumentType Objects Information about the declarations needed to process a document.
Document Document Objects Object which represents an entire document.
Element Element Objects Element nodes in the document hierarchy.
Attr Attr Objects Attribute value nodes on element nodes.
Comment Comment Objects Representation of comments in the source document.
Text Text and CDATASection Objects Nodes containing textual content from the document.
ProcessingInstruction ProcessingInstruction Objects Processing instruction representation. An additional section describes the exceptions defined for working with the DOM in Python. DOMImplementation Objects The DOMImplementation interface provides a way for applications to determine the availability of particular features in the DOM they are using. DOM Level 2 added the ability to create new Document and DocumentType objects using the DOMImplementation as well.
DOMImplementation.hasFeature(feature, version)
Return True if the feature identified by the pair of strings feature and version is implemented.
DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)
Return a new Document object (the root of the DOM), with a child Element object having the given namespaceUri and qualifiedName. The doctype must be a DocumentType object created by createDocumentType(), or None. In the Python DOM API, the first two arguments can also be None in order to indicate that no Element child is to be created.
DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)
Return a new DocumentType object that encapsulates the given qualifiedName, publicId, and systemId strings, representing the information contained in an XML document type declaration.
Node Objects All of the components of an XML document are subclasses of Node.
Node.nodeType
An integer representing the node type. Symbolic constants for the types are on the Node object: ELEMENT_NODE, ATTRIBUTE_NODE, TEXT_NODE, CDATA_SECTION_NODE, ENTITY_NODE, PROCESSING_INSTRUCTION_NODE, COMMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, NOTATION_NODE. This is a read-only attribute.
Node.parentNode
The parent of the current node, or None for the document node. The value is always a Node object or None. For Element nodes, this will be the parent element, except for the root element, in which case it will be the Document object. For Attr nodes, this is always None. This is a read-only attribute.
Node.attributes
A NamedNodeMap of attribute objects. Only elements have actual values for this; others provide None for this attribute. This is a read-only attribute.
Node.previousSibling
The node that immediately precedes this one with the same parent. For instance the element with an end-tag that comes just before the self element’s start-tag. Of course, XML documents are made up of more than just elements so the previous sibling could be text, a comment, or something else. If this node is the first child of the parent, this attribute will be None. This is a read-only attribute.
Node.nextSibling
The node that immediately follows this one with the same parent. See also previousSibling. If this is the last child of the parent, this attribute will be None. This is a read-only attribute.
Node.childNodes
A list of nodes contained within this node. This is a read-only attribute.
Node.firstChild
The first child of the node, if there are any, or None. This is a read-only attribute.
Node.lastChild
The last child of the node, if there are any, or None. This is a read-only attribute.
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
The namespace associated with the element name. This will be a string or None. This is a read-only attribute.
Node.nodeName
This has a different meaning for each node type; see the DOM specification for details. 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. For all node types, the value of this attribute will be either a string or None. This is a read-only attribute.
Node.nodeValue
This has a different meaning for each node type; see the DOM specification for details. The situation is similar to that with nodeName. The value is a string or None.
Node.hasAttributes()
Return True if the node has any attributes.
Node.hasChildNodes()
Return True if the node has any child nodes.
Node.isSameNode(other)
Return True if other refers to the same node as this node. This is especially useful for DOM implementations which use any sort of proxy architecture (because more than one object can refer to the same node). Note This is based on a proposed DOM Level 3 API which is still in the “working draft” stage, but this particular interface appears uncontroversial. Changes from the W3C will not necessarily affect this method in the Python DOM interface (though any new W3C API for this would also be supported).
Node.appendChild(newChild)
Add a new child node to this node at the end of the list of children, returning newChild. If the node was already in the tree, it is removed first.
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, ValueError 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, ValueError 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, ValueError is raised.
Node.normalize()
Join adjacent text nodes so that all stretches of text are stored as single Text instances. This simplifies processing text from a DOM tree for many applications.
Node.cloneNode(deep)
Clone this node. Setting deep means to clone all child nodes as well. This returns the clone.
NodeList Objects 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. The DOM Level 2 recommendation defines one method and one attribute for these objects:
NodeList.item(i)
Return the i’th item from the sequence, if there is one, or None. The index i is not allowed to be less than zero or greater than or equal to the length of the sequence.
NodeList.length
The number of nodes in the sequence.
In addition, the Python DOM interface requires that some additional support is provided to allow NodeList objects to be used as Python sequences. All NodeList implementations must include support for __len__() and __getitem__(); this allows iteration over the NodeList in for statements and proper support for the len() built-in function. If a DOM implementation supports modification of the document, the NodeList implementation must also support the __setitem__() and __delitem__() methods. DocumentType Objects Information about the notations and entities declared by a document (including the external subset if the parser uses it and can provide the information) is available from a DocumentType object. The DocumentType for a document is available from the Document object’s doctype attribute; if there is no DOCTYPE declaration for the document, the document’s doctype attribute will be set to None instead of an instance of this interface. DocumentType is a specialization of Node, and adds the following attributes:
DocumentType.publicId
The public identifier for the external subset of the document type definition. This will be a string or None.
DocumentType.systemId
The system identifier for the external subset of the document type definition. This will be a URI as a string, or None.
DocumentType.internalSubset
A string giving the complete internal subset from the document. This does not include the brackets which enclose the subset. If the document has no internal subset, this should be None.
DocumentType.name
The name of the root element as given in the DOCTYPE declaration, if present.
DocumentType.entities
This is a NamedNodeMap 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 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 Objects A Document represents an entire XML document, including its constituent elements, attributes, processing instructions, comments etc. Remember that it inherits properties from Node.
Document.documentElement
The one and only root element of the document.
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 and return a text node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree.
Document.createComment(data)
Create and return a comment node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree.
Document.createProcessingInstruction(target, data)
Create and return a processing instruction node containing the target and data passed as parameters. As with the other creation methods, this one does not insert the node into the tree.
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.getElementsByTagName(tagName)
Search for all descendants (direct children, children’s children, etc.) with a particular element type name.
Document.getElementsByTagNameNS(namespaceURI, localName)
Search for all descendants (direct children, children’s children, etc.) with a particular namespace URI and localname. The localname is the part of the namespace after the prefix.
Element Objects Element is a subclass of Node, so inherits all the attributes of that class.
Element.tagName
The element type name. In a namespace-using document it may have colons in it. The value is a string.
Element.getElementsByTagName(tagName)
Same as equivalent method in the Document class.
Element.getElementsByTagNameNS(namespaceURI, localName)
Same as equivalent method in the Document class.
Element.hasAttribute(name)
Return True if the element has an attribute named by name.
Element.hasAttributeNS(namespaceURI, localName)
Return True if the element has an attribute named by namespaceURI and localName.
Element.getAttribute(name)
Return the value of the attribute named by name as a string. If no such attribute exists, an empty string is returned, as if the attribute had no value.
Element.getAttributeNode(attrname)
Return the Attr node for the attribute named by attrname.
Element.getAttributeNS(namespaceURI, localName)
Return the value of the attribute named by namespaceURI and localName as a string. If no such attribute exists, an empty string is returned, as if the attribute had no value.
Element.getAttributeNodeNS(namespaceURI, localName)
Return an attribute value as a node, given a namespaceURI and localName.
Element.removeAttribute(name)
Remove an attribute by name. If there is no matching attribute, a NotFoundErr is raised.
Element.removeAttributeNode(oldAttr)
Remove and return oldAttr from the attribute list, if present. If oldAttr is not present, NotFoundErr is raised.
Element.removeAttributeNS(namespaceURI, localName)
Remove an attribute by name. Note that it uses a localName, not a qname. No exception is raised if there is no matching attribute.
Element.setAttribute(name, value)
Set an attribute value from a string.
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)
Set an attribute value from a string, given a namespaceURI and a qname. Note that a qname is the whole attribute name. This is different than above.
Attr Objects Attr inherits from Node, so inherits all its attributes.
Attr.name
The attribute name. In a namespace-using document it may include a colon.
Attr.localName
The part of the name following the colon if there is one, else the entire name. This is a read-only attribute.
Attr.prefix
The part of the name preceding the colon if there is one, else the empty string.
Attr.value
The text value of the attribute. This is a synonym for the nodeValue attribute.
NamedNodeMap Objects NamedNodeMap does not inherit from Node.
NamedNodeMap.length
The length of the attribute list.
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.
There are also experimental methods that give this class more mapping behavior. You can use them or you can use the standardized getAttribute*() family of methods on the Element objects. Comment Objects Comment represents a comment in the XML document. It is a subclass of Node, but cannot have child nodes.
Comment.data
The content of the comment as a string. The attribute contains all characters between the leading <!-- and trailing -->, but does not include them.
Text and CDATASection Objects 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. These interfaces extend the Node interface. They cannot have child nodes.
Text.data
The content of the text node as a string.
Note The use of a CDATASection node does not indicate that the node represents a complete CDATA marked section, only that the content of the node was part of a CDATA section. A single CDATA section may be represented by more than one node in the document tree. There is no way to determine whether two adjacent CDATASection nodes represent different CDATA marked sections. ProcessingInstruction Objects Represents a processing instruction in the XML document; this inherits from the Node interface and cannot have child nodes.
ProcessingInstruction.target
The content of the processing instruction up to the first whitespace character. This is a read-only attribute.
ProcessingInstruction.data
The content of the processing instruction following the first whitespace character.
Exceptions The DOM Level 2 recommendation defines a single exception, DOMException, and a number of constants that allow applications to determine what sort of error occurred. DOMException instances carry a code attribute that provides the appropriate value for the specific exception. The Python DOM interface provides the constants, but also expands the set of exceptions so that a specific exception exists for each of the exception codes defined by the DOM. The implementations must raise the appropriate specific exception, each of which carries the appropriate value for the code attribute.
exception xml.dom.DOMException
Base exception class used for all specific DOM exceptions. This exception class cannot be directly instantiated.
exception xml.dom.DomstringSizeErr
Raised when a specified range of text does not fit into a string. 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.HierarchyRequestErr
Raised when an attempt is made to insert a node where the node type is not allowed.
exception xml.dom.IndexSizeErr
Raised when an index or size parameter to a method is negative or exceeds the allowed values.
exception xml.dom.InuseAttributeErr
Raised when an attempt is made to insert an Attr node that is already present elsewhere in the document.
exception xml.dom.InvalidAccessErr
Raised if a parameter or an operation is not supported on the underlying object.
exception xml.dom.InvalidCharacterErr
This exception is raised when a string parameter contains a character that is not permitted in the context it’s being used in by the XML 1.0 recommendation. For example, attempting to create an Element node with a space in the element type name will cause this error to be raised.
exception xml.dom.InvalidModificationErr
Raised when an attempt is made to modify the type of a node.
exception xml.dom.InvalidStateErr
Raised when an attempt is made to use an object that is not defined or is no longer usable.
exception xml.dom.NamespaceErr
If an attempt is made to change any object in a way that is not permitted with regard to the Namespaces in XML recommendation, this exception is raised.
exception xml.dom.NotFoundErr
Exception when a node does not exist in the referenced context. For example, NamedNodeMap.removeNamedItem() will raise this if the node passed in does not exist in the map.
exception xml.dom.NotSupportedErr
Raised when the implementation does not support the requested type of object or operation.
exception xml.dom.NoDataAllowedErr
This is raised if data is specified for a node which does not support data.
exception xml.dom.NoModificationAllowedErr
Raised on attempts to modify an object where modifications are not allowed (such as for read-only nodes).
exception xml.dom.SyntaxErr
Raised when an invalid or illegal string is specified.
exception xml.dom.WrongDocumentErr
Raised when a node is inserted in a different document than it currently belongs to, and the implementation does not support migrating the node from one document to the other.
The exception codes defined in the DOM recommendation map to the exceptions described above according to this table:
Constant Exception
DOMSTRING_SIZE_ERR DomstringSizeErr
HIERARCHY_REQUEST_ERR HierarchyRequestErr
INDEX_SIZE_ERR IndexSizeErr
INUSE_ATTRIBUTE_ERR InuseAttributeErr
INVALID_ACCESS_ERR InvalidAccessErr
INVALID_CHARACTER_ERR InvalidCharacterErr
INVALID_MODIFICATION_ERR InvalidModificationErr
INVALID_STATE_ERR InvalidStateErr
NAMESPACE_ERR NamespaceErr
NOT_FOUND_ERR NotFoundErr
NOT_SUPPORTED_ERR NotSupportedErr
NO_DATA_ALLOWED_ERR NoDataAllowedErr
NO_MODIFICATION_ALLOWED_ERR NoModificationAllowedErr
SYNTAX_ERR SyntaxErr
WRONG_DOCUMENT_ERR WrongDocumentErr Conformance This section describes the conformance requirements and relationships between the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for Python. Type Mapping The IDL types used in the DOM specification are mapped to Python types according to the following table.
IDL Type Python Type
boolean bool or int
int int
long int int
unsigned int int
DOMString str or bytes
null None Accessor Methods The mapping from OMG IDL to Python defines accessor functions for IDL attribute declarations in much the way the Java mapping does. Mapping the IDL declarations 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. The Python DOM API, however, does require that normal attribute access work. This means that the typical surrogates generated by Python IDL compilers are not likely to work, and wrapper objects may be needed on the client if the DOM objects are accessed via CORBA. While this does require some additional consideration for CORBA DOM clients, the implementers with experience using DOM over CORBA from Python do not consider this a problem. Attributes that are declared readonly may not restrict write access in all DOM implementations. In the Python DOM API, accessor functions are not required. If provided, they should take the form defined by the Python IDL mapping, but these methods are considered unnecessary since the attributes are accessible directly from Python. “Set” accessors should never be provided for readonly attributes. 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. | python.library.xml.dom |
Attr.localName
The part of the name following the colon if there is one, else the entire name. This is a read-only attribute. | python.library.xml.dom#xml.dom.Attr.localName |
Attr.name
The attribute name. In a namespace-using document it may include a colon. | python.library.xml.dom#xml.dom.Attr.name |
Attr.prefix
The part of the name preceding the colon if there is one, else the empty string. | python.library.xml.dom#xml.dom.Attr.prefix |
Attr.value
The text value of the attribute. This is a synonym for the nodeValue attribute. | python.library.xml.dom#xml.dom.Attr.value |
Comment.data
The content of the comment as a string. The attribute contains all characters between the leading <!-- and trailing -->, but does not include them. | python.library.xml.dom#xml.dom.Comment.data |
Document.createAttribute(name)
Create and return an attribute node. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance. | python.library.xml.dom#xml.dom.Document.createAttribute |
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. | python.library.xml.dom#xml.dom.Document.createAttributeNS |
Document.createComment(data)
Create and return a comment node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree. | python.library.xml.dom#xml.dom.Document.createComment |
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(). | python.library.xml.dom#xml.dom.Document.createElement |
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(). | python.library.xml.dom#xml.dom.Document.createElementNS |
Document.createProcessingInstruction(target, data)
Create and return a processing instruction node containing the target and data passed as parameters. As with the other creation methods, this one does not insert the node into the tree. | python.library.xml.dom#xml.dom.Document.createProcessingInstruction |
Document.createTextNode(data)
Create and return a text node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree. | python.library.xml.dom#xml.dom.Document.createTextNode |
Document.documentElement
The one and only root element of the document. | python.library.xml.dom#xml.dom.Document.documentElement |
Document.getElementsByTagName(tagName)
Search for all descendants (direct children, children’s children, etc.) with a particular element type name. | python.library.xml.dom#xml.dom.Document.getElementsByTagName |
Document.getElementsByTagNameNS(namespaceURI, localName)
Search for all descendants (direct children, children’s children, etc.) with a particular namespace URI and localname. The localname is the part of the namespace after the prefix. | python.library.xml.dom#xml.dom.Document.getElementsByTagNameNS |
DocumentType.entities
This is a NamedNodeMap 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. | python.library.xml.dom#xml.dom.DocumentType.entities |
DocumentType.internalSubset
A string giving the complete internal subset from the document. This does not include the brackets which enclose the subset. If the document has no internal subset, this should be None. | python.library.xml.dom#xml.dom.DocumentType.internalSubset |
DocumentType.name
The name of the root element as given in the DOCTYPE declaration, if present. | python.library.xml.dom#xml.dom.DocumentType.name |
DocumentType.notations
This is a NamedNodeMap 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. | python.library.xml.dom#xml.dom.DocumentType.notations |
DocumentType.publicId
The public identifier for the external subset of the document type definition. This will be a string or None. | python.library.xml.dom#xml.dom.DocumentType.publicId |
DocumentType.systemId
The system identifier for the external subset of the document type definition. This will be a URI as a string, or None. | python.library.xml.dom#xml.dom.DocumentType.systemId |
exception xml.dom.DOMException
Base exception class used for all specific DOM exceptions. This exception class cannot be directly instantiated. | python.library.xml.dom#xml.dom.DOMException |
DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)
Return a new Document object (the root of the DOM), with a child Element object having the given namespaceUri and qualifiedName. The doctype must be a DocumentType object created by createDocumentType(), or None. In the Python DOM API, the first two arguments can also be None in order to indicate that no Element child is to be created. | python.library.xml.dom#xml.dom.DOMImplementation.createDocument |
DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)
Return a new DocumentType object that encapsulates the given qualifiedName, publicId, and systemId strings, representing the information contained in an XML document type declaration. | python.library.xml.dom#xml.dom.DOMImplementation.createDocumentType |
DOMImplementation.hasFeature(feature, version)
Return True if the feature identified by the pair of strings feature and version is implemented. | python.library.xml.dom#xml.dom.DOMImplementation.hasFeature |
exception xml.dom.DomstringSizeErr
Raised when a specified range of text does not fit into a string. This is not known to be used in the Python DOM implementations, but may be received from DOM implementations not written in Python. | python.library.xml.dom#xml.dom.DomstringSizeErr |
Element.getAttribute(name)
Return the value of the attribute named by name as a string. If no such attribute exists, an empty string is returned, as if the attribute had no value. | python.library.xml.dom#xml.dom.Element.getAttribute |
Element.getAttributeNode(attrname)
Return the Attr node for the attribute named by attrname. | python.library.xml.dom#xml.dom.Element.getAttributeNode |
Element.getAttributeNodeNS(namespaceURI, localName)
Return an attribute value as a node, given a namespaceURI and localName. | python.library.xml.dom#xml.dom.Element.getAttributeNodeNS |
Element.getAttributeNS(namespaceURI, localName)
Return the value of the attribute named by namespaceURI and localName as a string. If no such attribute exists, an empty string is returned, as if the attribute had no value. | python.library.xml.dom#xml.dom.Element.getAttributeNS |
Element.getElementsByTagName(tagName)
Same as equivalent method in the Document class. | python.library.xml.dom#xml.dom.Element.getElementsByTagName |
Element.getElementsByTagNameNS(namespaceURI, localName)
Same as equivalent method in the Document class. | python.library.xml.dom#xml.dom.Element.getElementsByTagNameNS |
Element.hasAttribute(name)
Return True if the element has an attribute named by name. | python.library.xml.dom#xml.dom.Element.hasAttribute |
Element.hasAttributeNS(namespaceURI, localName)
Return True if the element has an attribute named by namespaceURI and localName. | python.library.xml.dom#xml.dom.Element.hasAttributeNS |
Element.removeAttribute(name)
Remove an attribute by name. If there is no matching attribute, a NotFoundErr is raised. | python.library.xml.dom#xml.dom.Element.removeAttribute |
Element.removeAttributeNode(oldAttr)
Remove and return oldAttr from the attribute list, if present. If oldAttr is not present, NotFoundErr is raised. | python.library.xml.dom#xml.dom.Element.removeAttributeNode |
Element.removeAttributeNS(namespaceURI, localName)
Remove an attribute by name. Note that it uses a localName, not a qname. No exception is raised if there is no matching attribute. | python.library.xml.dom#xml.dom.Element.removeAttributeNS |
Element.setAttribute(name, value)
Set an attribute value from a string. | python.library.xml.dom#xml.dom.Element.setAttribute |
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. | python.library.xml.dom#xml.dom.Element.setAttributeNode |
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. | python.library.xml.dom#xml.dom.Element.setAttributeNodeNS |
Element.setAttributeNS(namespaceURI, qname, value)
Set an attribute value from a string, given a namespaceURI and a qname. Note that a qname is the whole attribute name. This is different than above. | python.library.xml.dom#xml.dom.Element.setAttributeNS |
Element.tagName
The element type name. In a namespace-using document it may have colons in it. The value is a string. | python.library.xml.dom#xml.dom.Element.tagName |
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. | python.library.xml.dom#xml.dom.EMPTY_NAMESPACE |
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. 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. | python.library.xml.dom#xml.dom.getDOMImplementation |
exception xml.dom.HierarchyRequestErr
Raised when an attempt is made to insert a node where the node type is not allowed. | python.library.xml.dom#xml.dom.HierarchyRequestErr |
exception xml.dom.IndexSizeErr
Raised when an index or size parameter to a method is negative or exceeds the allowed values. | python.library.xml.dom#xml.dom.IndexSizeErr |
exception xml.dom.InuseAttributeErr
Raised when an attempt is made to insert an Attr node that is already present elsewhere in the document. | python.library.xml.dom#xml.dom.InuseAttributeErr |
exception xml.dom.InvalidAccessErr
Raised if a parameter or an operation is not supported on the underlying object. | python.library.xml.dom#xml.dom.InvalidAccessErr |
exception xml.dom.InvalidCharacterErr
This exception is raised when a string parameter contains a character that is not permitted in the context it’s being used in by the XML 1.0 recommendation. For example, attempting to create an Element node with a space in the element type name will cause this error to be raised. | python.library.xml.dom#xml.dom.InvalidCharacterErr |
exception xml.dom.InvalidModificationErr
Raised when an attempt is made to modify the type of a node. | python.library.xml.dom#xml.dom.InvalidModificationErr |
exception xml.dom.InvalidStateErr
Raised when an attempt is made to use an object that is not defined or is no longer usable. | python.library.xml.dom#xml.dom.InvalidStateErr |
xml.dom.minidom — Minimal DOM implementation Source code: Lib/xml/dom/minidom.py xml.dom.minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller. Users who are not already proficient with the DOM should consider using the xml.etree.ElementTree module for their XML processing instead. Warning The xml.dom.minidom module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities. DOM applications typically start by parsing some XML into a DOM. With xml.dom.minidom, this is done through the parse functions: from xml.dom.minidom import parse, parseString
dom1 = parse('c:\\temp\\mydata.xml') # parse an XML file by name
datasource = open('c:\\temp\\mydata.xml')
dom2 = parse(datasource) # parse an open file
dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')
The parse() function can take either a filename or an open file object.
xml.dom.minidom.parse(filename_or_file, parser=None, bufsize=None)
Return a Document from the given input. filename_or_file may be either a file name, or a file-like object. parser, if given, must be a SAX2 parser object. This function will change the document handler of the parser and activate namespace support; other parser configuration (like setting an entity resolver) must have been done in advance.
If you have XML in a string, you can use the parseString() function instead:
xml.dom.minidom.parseString(string, parser=None)
Return a Document that represents the string. This method creates an io.StringIO object for the string and passes that on to parse().
Both functions return a Document object representing the content of the document. What the parse() and parseString() functions do is connect an XML parser with a “DOM builder” that can accept parse events from any SAX parser and convert them into a DOM tree. The name of the functions are perhaps misleading, but are easy to grasp when learning the interfaces. The parsing of the document will be completed before these functions return; it’s simply that these functions do not provide a parser implementation themselves. You can also create a Document by calling a method on a “DOM Implementation” object. You can get this object either by calling the getDOMImplementation() function in the xml.dom package or the xml.dom.minidom module. Once you have a Document, you can add child nodes to it to populate the DOM: from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
newdoc = impl.createDocument(None, "some_tag", None)
top_element = newdoc.documentElement
text = newdoc.createTextNode('Some textual content.')
top_element.appendChild(text)
Once you have a DOM document object, you can access the parts of your XML document through its properties and methods. These properties are defined in the DOM specification. The main property of the document object is the documentElement property. It gives you the main element in the XML document: the one that holds all others. Here is an example program: dom3 = parseString("<myxml>Some data</myxml>")
assert dom3.documentElement.tagName == "myxml"
When you are finished with a DOM tree, you may optionally call the unlink() method to encourage early cleanup of the now-unneeded objects. unlink() is an xml.dom.minidom-specific extension to the DOM API that renders the node and its descendants are essentially useless. Otherwise, Python’s garbage collector will eventually take care of the objects in the tree. See also Document Object Model (DOM) Level 1 Specification
The W3C recommendation for the DOM supported by xml.dom.minidom. DOM Objects The definition of the DOM API for Python is given as part of the xml.dom module documentation. This section lists the differences between the API and xml.dom.minidom.
Node.unlink()
Break internal references within the DOM so that it will be garbage collected on versions of Python without cyclic GC. Even when cyclic GC is available, using this can make large amounts of memory available sooner, so calling this on DOM objects as soon as they are no longer needed is good practice. This only needs to be called on the Document object, but may be called on child nodes to discard children of that node. You can avoid calling this method explicitly by using the with statement. The following code will automatically unlink dom when the with block is exited: with xml.dom.minidom.parse(datasource) as dom:
... # Work with dom.
Node.writexml(writer, indent="", addindent="", newl="", encoding=None, standalone=None)
Write XML to the writer object. The writer receives texts but not bytes as input, it should have a write() method which matches that of the file object interface. The indent parameter is the indentation of the current node. The addindent parameter is the incremental indentation to use for subnodes of the current one. The newl parameter specifies the string to use to terminate newlines. For the Document node, an additional keyword argument encoding can be used to specify the encoding field of the XML header. Silimarly, explicitly stating the standalone argument causes the standalone document declarations to be added to the prologue of the XML document. If the value is set to True, standalone=”yes” is added, otherwise it is set to “no”. Not stating the argument will omit the declaration from the document. Changed in version 3.8: The writexml() method now preserves the attribute order specified by the user.
Node.toxml(encoding=None, standalone=None)
Return a string or byte string containing the XML represented by the DOM node. With an explicit encoding 1 argument, the result is a byte string in the specified encoding. With no encoding argument, the result is a Unicode string, and the XML declaration in the resulting string does not specify an encoding. Encoding this string in an encoding other than UTF-8 is likely incorrect, since UTF-8 is the default encoding of XML. The standalone argument behaves exactly as in writexml(). Changed in version 3.8: The toxml() method now preserves the attribute order specified by the user.
Node.toprettyxml(indent="\t", newl="\n", encoding=None, standalone=None)
Return a pretty-printed version of the document. indent specifies the indentation string and defaults to a tabulator; newl specifies the string emitted at the end of each line and defaults to \n. The encoding argument behaves like the corresponding argument of toxml(). The standalone argument behaves exactly as in writexml(). Changed in version 3.8: The toprettyxml() method now preserves the attribute order specified by the user.
DOM Example This example program is a fairly realistic example of a simple program. In this particular case, we do not take much advantage of the flexibility of the DOM. import xml.dom.minidom
document = """\
<slideshow>
<title>Demo slideshow</title>
<slide><title>Slide title</title>
<point>This is a demo</point>
<point>Of a program for processing slides</point>
</slide>
<slide><title>Another demo slide</title>
<point>It is important</point>
<point>To have more than</point>
<point>one slide</point>
</slide>
</slideshow>
"""
dom = xml.dom.minidom.parseString(document)
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
def handleSlideshow(slideshow):
print("<html>")
handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
slides = slideshow.getElementsByTagName("slide")
handleToc(slides)
handleSlides(slides)
print("</html>")
def handleSlides(slides):
for slide in slides:
handleSlide(slide)
def handleSlide(slide):
handleSlideTitle(slide.getElementsByTagName("title")[0])
handlePoints(slide.getElementsByTagName("point"))
def handleSlideshowTitle(title):
print("<title>%s</title>" % getText(title.childNodes))
def handleSlideTitle(title):
print("<h2>%s</h2>" % getText(title.childNodes))
def handlePoints(points):
print("<ul>")
for point in points:
handlePoint(point)
print("</ul>")
def handlePoint(point):
print("<li>%s</li>" % getText(point.childNodes))
def handleToc(slides):
for slide in slides:
title = slide.getElementsByTagName("title")[0]
print("<p>%s</p>" % getText(title.childNodes))
handleSlideshow(dom)
minidom and the DOM standard The xml.dom.minidom module is essentially a DOM 1.0-compatible DOM with some DOM 2 features (primarily namespace features). Usage of the DOM interface in Python is straight-forward. The following mapping rules apply: Interfaces are accessed through instance objects. Applications should not instantiate the classes themselves; they should use the creator functions available on the Document object. Derived interfaces support all operations (and attributes) from the base interfaces, plus any new operations. Operations are used as methods. Since the DOM uses only in parameters, the arguments are passed in normal order (from left to right). There are no optional arguments. void operations return None. IDL attributes map to instance attributes. For compatibility with the OMG IDL language mapping for Python, an attribute foo can also be accessed through accessor methods _get_foo() and _set_foo(). readonly attributes must not be changed; this is not enforced at runtime. The types short int, unsigned int, unsigned long long, and boolean all map to Python integer objects. The type DOMString maps to Python strings. xml.dom.minidom supports either bytes or strings, but will normally produce strings. Values of type DOMString may also be None where allowed to have the IDL null value by the DOM specification from the W3C.
const declarations map to variables in their respective scope (e.g. xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE); they must not be changed.
DOMException is currently not supported in xml.dom.minidom. Instead, xml.dom.minidom uses standard Python exceptions such as TypeError and AttributeError.
NodeList objects are implemented using Python’s built-in list type. These objects provide the interface defined in the DOM specification, but with earlier versions of Python they do not support the official API. They are, however, much more “Pythonic” than the interface defined in the W3C recommendations. The following interfaces have no implementation in xml.dom.minidom: DOMTimeStamp EntityReference Most of these reflect information in the XML document that is not of general utility to most DOM users. Footnotes
1
The encoding name included in the XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not valid in an XML document’s declaration, even though Python accepts it as an encoding name. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl and https://www.iana.org/assignments/character-sets/character-sets.xhtml. | python.library.xml.dom.minidom |
Node.toprettyxml(indent="\t", newl="\n", encoding=None, standalone=None)
Return a pretty-printed version of the document. indent specifies the indentation string and defaults to a tabulator; newl specifies the string emitted at the end of each line and defaults to \n. The encoding argument behaves like the corresponding argument of toxml(). The standalone argument behaves exactly as in writexml(). Changed in version 3.8: The toprettyxml() method now preserves the attribute order specified by the user. | python.library.xml.dom.minidom#xml.dom.minidom.Node.toprettyxml |
Node.toxml(encoding=None, standalone=None)
Return a string or byte string containing the XML represented by the DOM node. With an explicit encoding 1 argument, the result is a byte string in the specified encoding. With no encoding argument, the result is a Unicode string, and the XML declaration in the resulting string does not specify an encoding. Encoding this string in an encoding other than UTF-8 is likely incorrect, since UTF-8 is the default encoding of XML. The standalone argument behaves exactly as in writexml(). Changed in version 3.8: The toxml() method now preserves the attribute order specified by the user. | python.library.xml.dom.minidom#xml.dom.minidom.Node.toxml |
Node.unlink()
Break internal references within the DOM so that it will be garbage collected on versions of Python without cyclic GC. Even when cyclic GC is available, using this can make large amounts of memory available sooner, so calling this on DOM objects as soon as they are no longer needed is good practice. This only needs to be called on the Document object, but may be called on child nodes to discard children of that node. You can avoid calling this method explicitly by using the with statement. The following code will automatically unlink dom when the with block is exited: with xml.dom.minidom.parse(datasource) as dom:
... # Work with dom. | python.library.xml.dom.minidom#xml.dom.minidom.Node.unlink |
Node.writexml(writer, indent="", addindent="", newl="", encoding=None, standalone=None)
Write XML to the writer object. The writer receives texts but not bytes as input, it should have a write() method which matches that of the file object interface. The indent parameter is the indentation of the current node. The addindent parameter is the incremental indentation to use for subnodes of the current one. The newl parameter specifies the string to use to terminate newlines. For the Document node, an additional keyword argument encoding can be used to specify the encoding field of the XML header. Silimarly, explicitly stating the standalone argument causes the standalone document declarations to be added to the prologue of the XML document. If the value is set to True, standalone=”yes” is added, otherwise it is set to “no”. Not stating the argument will omit the declaration from the document. Changed in version 3.8: The writexml() method now preserves the attribute order specified by the user. | python.library.xml.dom.minidom#xml.dom.minidom.Node.writexml |
xml.dom.minidom.parse(filename_or_file, parser=None, bufsize=None)
Return a Document from the given input. filename_or_file may be either a file name, or a file-like object. parser, if given, must be a SAX2 parser object. This function will change the document handler of the parser and activate namespace support; other parser configuration (like setting an entity resolver) must have been done in advance. | python.library.xml.dom.minidom#xml.dom.minidom.parse |
xml.dom.minidom.parseString(string, parser=None)
Return a Document that represents the string. This method creates an io.StringIO object for the string and passes that on to parse(). | python.library.xml.dom.minidom#xml.dom.minidom.parseString |
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. | python.library.xml.dom#xml.dom.NamedNodeMap.item |
NamedNodeMap.length
The length of the attribute list. | python.library.xml.dom#xml.dom.NamedNodeMap.length |
exception xml.dom.NamespaceErr
If an attempt is made to change any object in a way that is not permitted with regard to the Namespaces in XML recommendation, this exception is raised. | python.library.xml.dom#xml.dom.NamespaceErr |
exception xml.dom.NoDataAllowedErr
This is raised if data is specified for a node which does not support data. | python.library.xml.dom#xml.dom.NoDataAllowedErr |
Node.appendChild(newChild)
Add a new child node to this node at the end of the list of children, returning newChild. If the node was already in the tree, it is removed first. | python.library.xml.dom#xml.dom.Node.appendChild |
Node.attributes
A NamedNodeMap of attribute objects. Only elements have actual values for this; others provide None for this attribute. This is a read-only attribute. | python.library.xml.dom#xml.dom.Node.attributes |
Node.childNodes
A list of nodes contained within this node. This is a read-only attribute. | python.library.xml.dom#xml.dom.Node.childNodes |
Node.cloneNode(deep)
Clone this node. Setting deep means to clone all child nodes as well. This returns the clone. | python.library.xml.dom#xml.dom.Node.cloneNode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.