os_environ
The default environment variables to be included in every request’s WSGI environment. By default, this is a copy of os.environ at the time that wsgiref.handlers was imported, but subclasses can either create their own at the class or instance level. Note that the dictionary should be considered read-only, since the default value is shared between multiple classes and instances.


run(app)
Run the specified WSGI application, app.


sendfile()
Override to implement platform-specific file transmission. This method is called only if the application’s return value is an instance of the class specified by the wsgi_file_wrapper attribute. It should return a true value if it was able to successfully transmit the file, so that the default transmission code will not be executed. The default implementation of this method just returns a false value.


server_software
If the origin_server attribute is set, this attribute’s value is used to set the default SERVER_SOFTWARE WSGI environment variable, and also to set a default Server: header in HTTP responses. It is ignored for handlers (such as BaseCGIHandler and CGIHandler) that are not HTTP origin servers.  Changed in version 3.3: The term “Python” is replaced with implementation specific term like “CPython”, “Jython” etc.


setup_environ()
Set the environ attribute to a fully-populated WSGI environment. The default implementation uses all of the above methods and attributes, plus the get_stdin(), get_stderr(), and add_cgi_vars() methods and the wsgi_file_wrapper attribute. It also inserts a SERVER_SOFTWARE key if not present, as long as the origin_server attribute is a true value and the server_software attribute is set.


traceback_limit
The maximum number of frames to include in tracebacks output by the default log_exception() method. If None, all frames are included.


wsgi_file_wrapper
A wsgi.file_wrapper factory, or None. The default value of this attribute is the wsgiref.util.FileWrapper class.


wsgi_multiprocess
The value to be used for the wsgi.multiprocess environment variable. It defaults to true in BaseHandler, but may have a different default (or be set by the constructor) in the other subclasses.


wsgi_multithread
The value to be used for the wsgi.multithread environment variable. It defaults to true in BaseHandler, but may have a different default (or be set by the constructor) in the other subclasses.


wsgi_run_once
The value to be used for the wsgi.run_once environment variable. It defaults to false in BaseHandler, but CGIHandler sets it to true by default.


_flush()
Force buffered data to be transmitted to the client. It’s okay if this method is a no-op (i.e., if _write() actually sends the data).


_write(data)
Buffer the bytes data for transmission to the client. It’s okay if this method actually transmits the data; BaseHandler just separates write and flush operations for greater efficiency when the underlying system actually has such a distinction.


class wsgiref.handlers.CGIHandler
CGI-based invocation via sys.stdin, sys.stdout, sys.stderr and os.environ. This is useful when you have a WSGI application and want to run it as a CGI script. Simply invoke CGIHandler().run(app), where app is the WSGI application object you wish to invoke. This class is a subclass of BaseCGIHandler that sets wsgi.run_once to true, wsgi.multithread to false, and wsgi.multiprocess to true, and always uses sys and os to obtain the necessary CGI streams and environment.


class wsgiref.handlers.IISCGIHandler
A specialized alternative to CGIHandler, for use when deploying on Microsoft’s IIS web server, without having set the config allowPathInfo option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7). By default, IIS gives a PATH_INFO that duplicates the SCRIPT_NAME at the front, causing problems for WSGI applications that wish to implement routing. This handler strips any such duplicated path. IIS can be configured to pass the correct PATH_INFO, but this causes another bug where PATH_TRANSLATED is wrong. Luckily this variable is rarely used and is not guaranteed by WSGI. On IIS<7, though, the setting can only be made on a vhost level, affecting all other script mappings, many of which break when exposed to the PATH_TRANSLATED bug. For this reason IIS<7 is almost never deployed with the fix (Even IIS7 rarely uses it because there is still no UI for it.). There is no way for CGI code to tell whether the option was set, so a separate handler class is provided. It is used in the same way as CGIHandler, i.e., by calling IISCGIHandler().run(app), where app is the WSGI application object you wish to invoke.  New in version 3.2.


wsgiref.handlers.read_environ()
Transcode CGI variables from os.environ to PEP 3333 “bytes in unicode” strings, returning a new dictionary. This function is used by CGIHandler and IISCGIHandler in place of directly using os.environ, which is not necessarily WSGI-compliant on all platforms and web servers using Python 3 – specifically, ones where the OS’s actual environment is Unicode (i.e. Windows), or ones where the environment is bytes, but the system encoding used by Python to decode it is anything other than ISO-8859-1 (e.g. Unix systems using UTF-8). If you are implementing a CGI-based handler of your own, you probably want to use this routine instead of just copying values out of os.environ directly.  New in version 3.2.


class wsgiref.handlers.SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)
Similar to BaseCGIHandler, but designed for use with HTTP origin servers. If you are writing an HTTP server implementation, you will probably want to subclass this instead of BaseCGIHandler. This class is a subclass of BaseHandler. It overrides the __init__(), get_stdin(), get_stderr(), add_cgi_vars(), _write(), and _flush() methods to support explicitly setting the environment and streams via the constructor. The supplied environment and streams are stored in the stdin, stdout, stderr, and environ attributes. The write() method of stdout should write each chunk in full, like io.BufferedIOBase.


class wsgiref.headers.Headers([headers])
Create a mapping-like object wrapping headers, which must be a list of header name/value tuples as described in PEP 3333. The default value of headers is an empty list. Headers objects support typical mapping operations including __getitem__(), get(), __setitem__(), setdefault(), __delitem__() and __contains__(). For each of these methods, the key is the header name (treated case-insensitively), and the value is the first value associated with that header name. Setting a header deletes any existing values for that header, then adds a new value at the end of the wrapped header list. Headers’ existing order is generally maintained, with new headers added to the end of the wrapped list. Unlike a dictionary, Headers objects do not raise an error when you try to get or delete a key that isn’t in the wrapped header list. Getting a nonexistent header just returns None, and deleting a nonexistent header does nothing. Headers objects also support keys(), values(), and items() methods. The lists returned by keys() and items() can include the same key more than once if there is a multi-valued header. The len() of a Headers object is the same as the length of its items(), which is the same as the length of the wrapped header list. In fact, the items() method just returns a copy of the wrapped header list. Calling bytes() on a Headers object returns a formatted bytestring suitable for transmission as HTTP response headers. Each header is placed on a line with its value, separated by a colon and a space. Each line is terminated by a carriage return and line feed, and the bytestring is terminated with a blank line. In addition to their mapping interface and formatting features, Headers objects also have the following methods for querying and adding multi-valued headers, and for adding headers with MIME parameters:
get_all(name)
Return a list of all the values for the named header. The returned list will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list.

add_header(name, value, **_params)
Add a (possibly multi-valued) header, with optional MIME parameters specified via keyword arguments. name is the header field to add. Keyword arguments can be used to set MIME parameters for the header field. Each parameter must be a string or None. Underscores in parameter names are converted to dashes, since dashes are illegal in Python identifiers, but many MIME parameter names include dashes. If the parameter value is a string, it is added to the header value parameters in the form name="value". If it is None, only the parameter name is added. (This is used for MIME parameters without a value.) Example usage: h.add_header('content-disposition', 'attachment', filename='bud.gif')
 The above will add a header that looks like this: Content-Disposition: attachment; filename="bud.gif"

  Changed in version 3.5: headers parameter is optional.


add_header(name, value, **_params)
Add a (possibly multi-valued) header, with optional MIME parameters specified via keyword arguments. name is the header field to add. Keyword arguments can be used to set MIME parameters for the header field. Each parameter must be a string or None. Underscores in parameter names are converted to dashes, since dashes are illegal in Python identifiers, but many MIME parameter names include dashes. If the parameter value is a string, it is added to the header value parameters in the form name="value". If it is None, only the parameter name is added. (This is used for MIME parameters without a value.) Example usage: h.add_header('content-disposition', 'attachment', filename='bud.gif')
 The above will add a header that looks like this: Content-Disposition: attachment; filename="bud.gif"


get_all(name)
Return a list of all the values for the named header. The returned list will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list.


wsgiref.simple_server.demo_app(environ, start_response)
This function is a small but complete WSGI application that returns a text page containing the message “Hello world!” and a list of the key/value pairs provided in the environ parameter. It’s useful for verifying that a WSGI server (such as wsgiref.simple_server) is able to run a simple WSGI application correctly.


wsgiref.simple_server.make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)
Create a new WSGI server listening on host and port, accepting connections for app. The return value is an instance of the supplied server_class, and will process requests using the specified handler_class. app must be a WSGI application object, as defined by PEP 3333. Example usage: from wsgiref.simple_server import make_server, demo_app

with make_server('', 8000, demo_app) as httpd:
    print("Serving HTTP on port 8000...")

    # Respond to requests until process is killed
    httpd.serve_forever()

    # Alternative: serve one request, then exit
    httpd.handle_request()


class wsgiref.simple_server.WSGIRequestHandler(request, client_address, server)
Create an HTTP handler for the given request (i.e. a socket), client_address (a (host,port) tuple), and server (WSGIServer instance). You do not need to create instances of this class directly; they are automatically created as needed by WSGIServer objects. You can, however, subclass this class and supply it as a handler_class to the make_server() function. Some possibly relevant methods for overriding in subclasses:
get_environ()
Returns a dictionary containing the WSGI environment for a request. The default implementation copies the contents of the WSGIServer object’s base_environ dictionary attribute and then adds various headers derived from the HTTP request. Each call to this method should return a new dictionary containing all of the relevant CGI environment variables as specified in PEP 3333.

get_stderr()
Return the object that should be used as the wsgi.errors stream. The default implementation just returns sys.stderr.

handle()
Process the HTTP request. The default implementation creates a handler instance using a wsgiref.handlers class to implement the actual WSGI application interface.


get_environ()
Returns a dictionary containing the WSGI environment for a request. The default implementation copies the contents of the WSGIServer object’s base_environ dictionary attribute and then adds various headers derived from the HTTP request. Each call to this method should return a new dictionary containing all of the relevant CGI environment variables as specified in PEP 3333.


get_stderr()
Return the object that should be used as the wsgi.errors stream. The default implementation just returns sys.stderr.


handle()
Process the HTTP request. The default implementation creates a handler instance using a wsgiref.handlers class to implement the actual WSGI application interface.


class wsgiref.simple_server.WSGIServer(server_address, RequestHandlerClass)
Create a WSGIServer instance. server_address should be a (host,port) tuple, and RequestHandlerClass should be the subclass of http.server.BaseHTTPRequestHandler that will be used to process requests. You do not normally need to call this constructor, as the make_server() function can handle all the details for you. WSGIServer is a subclass of http.server.HTTPServer, so all of its methods (such as serve_forever() and handle_request()) are available. WSGIServer also provides these WSGI-specific methods:
set_app(application)
Sets the callable application as the WSGI application that will receive requests.

get_app()
Returns the currently-set application callable.
 Normally, however, you do not need to use these additional methods, as set_app() is normally called by make_server(), and the get_app() exists mainly for the benefit of request handler instances.


get_app()
Returns the currently-set application callable.


set_app(application)
Sets the callable application as the WSGI application that will receive requests.


wsgiref.util.application_uri(environ)
Similar to request_uri(), except that the PATH_INFO and QUERY_STRING variables are ignored. The result is the base URI of the application object addressed by the request.


class wsgiref.util.FileWrapper(filelike, blksize=8192)
A wrapper to convert a file-like object to an iterator. The resulting objects support both __getitem__() and __iter__() iteration styles, for compatibility with Python 2.1 and Jython. As the object is iterated over, the optional blksize parameter will be repeatedly passed to the filelike object’s read() method to obtain bytestrings to yield. When read() returns an empty bytestring, iteration is ended and is not resumable. If filelike has a close() method, the returned object will also have a close() method, and it will invoke the filelike object’s close() method when called. Example usage: from io import StringIO
from wsgiref.util import FileWrapper

# We're using a StringIO-buffer for as the file-like object
filelike = StringIO("This is an example file-like object"*10)
wrapper = FileWrapper(filelike, blksize=5)

for chunk in wrapper:
    print(chunk)
  Deprecated since version 3.8: Support for sequence protocol is deprecated.


wsgiref.util.guess_scheme(environ)
Return a guess for whether wsgi.url_scheme should be “http” or “https”, by checking for a HTTPS environment variable in the environ dictionary. The return value is a string. This function is useful when creating a gateway that wraps CGI or a CGI-like protocol such as FastCGI. Typically, servers providing such protocols will include a HTTPS variable with a value of “1”, “yes”, or “on” when a request is received via SSL. So, this function returns “https” if such a value is found, and “http” otherwise.


wsgiref.util.is_hop_by_hop(header_name)
Return True if ‘header_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined by RFC 2616.


wsgiref.util.request_uri(environ, include_query=True)
Return the full request URI, optionally including the query string, using the algorithm found in the “URL Reconstruction” section of PEP 3333. If include_query is false, the query string is not included in the resulting URI.


wsgiref.util.setup_testing_defaults(environ)
Update environ with trivial defaults for testing purposes. This routine adds various parameters required for WSGI, including HTTP_HOST, SERVER_NAME, SERVER_PORT, REQUEST_METHOD, SCRIPT_NAME, PATH_INFO, and all of the PEP 3333-defined wsgi.* variables. It only supplies default values, and does not replace any existing settings for these variables. This routine is intended to make it easier for unit tests of WSGI servers and applications to set up dummy environments. It should NOT be used by actual WSGI servers or applications, since the data is fake! Example usage: from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server

# A relatively simple WSGI application. It's going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]

    start_response(status, headers)

    ret = [("%s: %s\n" % (key, value)).encode("utf-8")
           for key, value in environ.items()]
    return ret

with make_server('', 8000, simple_app) as httpd:
    print("Serving on port 8000...")
    httpd.serve_forever()


wsgiref.util.shift_path_info(environ)
Shift a single name from PATH_INFO to SCRIPT_NAME and return the name. The environ dictionary is modified in-place; use a copy if you need to keep the original PATH_INFO or SCRIPT_NAME intact. If there are no remaining path segments in PATH_INFO, None is returned. Typically, this routine is used to process each portion of a request URI path, for example to treat the path as a series of dictionary keys. This routine modifies the passed-in environment to make it suitable for invoking another WSGI application that is located at the target URI. For example, if there is a WSGI application at /foo, and the request URI path is /foo/bar/baz, and the WSGI application at /foo calls shift_path_info(), it will receive the string “bar”, and the environment will be updated to be suitable for passing to a WSGI application at /foo/bar. That is, SCRIPT_NAME will change from /foo to /foo/bar, and PATH_INFO will change from /bar/baz to /baz. When PATH_INFO is just a “/”, this routine returns an empty string and appends a trailing slash to SCRIPT_NAME, even though empty path segments are normally ignored, and SCRIPT_NAME doesn’t normally end in a slash. This is intentional behavior, to ensure that an application can tell the difference between URIs ending in /x from ones ending in /x/ when using this routine to do object traversal.


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()


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)


exception xdrlib.ConversionError
Class derived from Error. Contains no additional instance variables.


exception xdrlib.Error
The base exception class. Error has a single public attribute msg containing the description of the error.


class xdrlib.Packer
Packer is the class for packing data into XDR representation. The Packer class is instantiated with no arguments.


Packer.get_buffer()
Returns the current pack buffer as a string.


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.


Packer.pack_bytes(bytes)
Packs a variable length byte stream, similarly to pack_string().


Packer.pack_double(value)
Packs the double-precision floating point number value.


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_float(value)
Packs the single-precision floating point number value.


Packer.pack_fopaque(n, data)
Packs a fixed length opaque data stream, similarly to pack_fstring().


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_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_opaque(data)
Packs a variable length opaque data string, similarly to pack_string().


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.reset()
Resets the pack buffer to the empty string.


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.


Unpacker.done()
Indicates unpack completion. Raises an Error exception if all of the data has not been unpacked.


Unpacker.get_buffer()
Returns the current unpack data buffer as a string.


Unpacker.get_position()
Returns the current unpack position in the data buffer.


Unpacker.reset(data)
Resets the string buffer with the given data.


Unpacker.set_position(position)
Sets the data buffer unpack position to position. You should be careful about using get_position() and 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.


Unpacker.unpack_bytes()
Unpacks and returns a variable length byte stream, similarly to unpack_string().


Unpacker.unpack_double()
Unpacks a double-precision floating point number, similarly to unpack_float().


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_float()
Unpacks a single-precision floating point number.


Unpacker.unpack_fopaque(n)
Unpacks and returns a fixed length opaque data stream, similarly to unpack_fstring().


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_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_opaque()
Unpacks and returns a variable length opaque data string, similarly to unpack_string().


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().


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.


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.name
The attribute name. In a namespace-using document it may include a colon.


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.


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.


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.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.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.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.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.documentElement
The one and only root element of the document.


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.


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.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.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.


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.


exception xml.dom.DOMException
Base exception class used for all specific DOM exceptions. This exception class cannot be directly instantiated.


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.


DOMImplementation.hasFeature(feature, version)
Return True if the feature identified by the pair of strings feature and version is implemented.


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.


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.getAttributeNodeNS(namespaceURI, localName)
Return an attribute value as a node, given a namespaceURI and localName.


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.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.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.


Element.tagName
The element type name. In a namespace-using document it may have colons in it. The value is a string.


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.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.


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.


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("")
    handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
    slides = slideshow.getElementsByTagName("slide")
    handleToc(slides)
    handleSlides(slides)
    print("")

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("
%s
" % getText(title.childNodes))

def handlePoints(points):
    print("
")
    for point in points:
        handlePoint(point)
    print("
")

def handlePoint(point):
    print("
%s
" % getText(point.childNodes))

def handleToc(slides):
    for slide in slides:
        title = slide.getElementsByTagName("title")[0]
        print("
%s
" % 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.


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.


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.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.


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.


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().


NamedNodeMap.item(index)
Return an attribute with a particular index. The order you get the attributes in is arbitrary but will be consistent for the life of a DOM. Each item is an attribute node. Get its value with the value attribute.


NamedNodeMap.length
The length of the attribute list.


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.NoDataAllowedErr
This is raised if data is specified for a node which does not support data.


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.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.childNodes
A list of nodes contained within this node. This is a read-only attribute.


Node.cloneNode(deep)
Clone this node. Setting deep means to clone all child nodes as well. This returns the clone.


Node.firstChild
The first child of the node, if there are any, or None. This is a read-only attribute.


Node.hasAttributes()
Return True if the node has any attributes.


Node.hasChildNodes()
Return True if the node has any child nodes.


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.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.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.namespaceURI
The namespace associated with the element name. This will be a string or 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.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.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.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.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.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.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.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.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.


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.


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.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.


ProcessingInstruction.data
The content of the processing instruction following the first whitespace character.


ProcessingInstruction.target
The content of the processing instruction up to the first whitespace character. This is a read-only attribute.


xml.dom.pulldom — Support for building partial DOM trees Source code: Lib/xml/dom/pulldom.py The xml.dom.pulldom module provides a “pull parser” which can also be asked to produce DOM-accessible fragments of the document where necessary. The basic concept involves pulling “events” from a stream of incoming XML and processing them. In contrast to SAX which also employs an event-driven processing model together with callbacks, the user of a pull parser is responsible for explicitly pulling events from the stream, looping over those events until either processing is finished or an error condition occurs.  Warning The xml.dom.pulldom module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.   Changed in version 3.7.1: The SAX parser no longer processes general external entities by default to increase security by default. To enable processing of external entities, pass a custom parser instance in: from xml.dom.pulldom import parse
from xml.sax import make_parser
from xml.sax.handler import feature_external_ges

parser = make_parser()
parser.setFeature(feature_external_ges, True)
parse(filename, parser=parser)
  Example: from xml.dom import pulldom

doc = pulldom.parse('sales_items.xml')
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'item':
        if int(node.getAttribute('price')) > 50:
            doc.expandNode(node)
            print(node.toxml())
 event is a constant and can be one of:  START_ELEMENT END_ELEMENT COMMENT START_DOCUMENT END_DOCUMENT CHARACTERS PROCESSING_INSTRUCTION IGNORABLE_WHITESPACE  node is an object of type xml.dom.minidom.Document, xml.dom.minidom.Element or xml.dom.minidom.Text. Since the document is treated as a “flat” stream of events, the document “tree” is implicitly traversed and the desired elements are found regardless of their depth in the tree. In other words, one does not need to consider hierarchical issues such as recursive searching of the document nodes, although if the context of elements were important, one would either need to maintain some context-related state (i.e. remembering where one is in the document at any given point) or to make use of the DOMEventStream.expandNode() method and switch to DOM-related processing.
class xml.dom.pulldom.PullDom(documentFactory=None)
Subclass of xml.sax.handler.ContentHandler.

class xml.dom.pulldom.SAX2DOM(documentFactory=None)
Subclass of xml.sax.handler.ContentHandler.

xml.dom.pulldom.parse(stream_or_string, parser=None, bufsize=None)
Return a DOMEventStream from the given input. stream_or_string may be either a file name, or a file-like object. parser, if given, must be an XMLReader 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.pulldom.parseString(string, parser=None)
Return a DOMEventStream that represents the (Unicode) string.

xml.dom.pulldom.default_bufsize
Default value for the bufsize parameter to parse(). The value of this variable can be changed before calling parse() and the new value will take effect.
 DOMEventStream Objects
class xml.dom.pulldom.DOMEventStream(stream, parser, bufsize)
 Deprecated since version 3.8: Support for sequence protocol is deprecated.
getEvent()
Return a tuple containing event and the current node as xml.dom.minidom.Document if event equals START_DOCUMENT, xml.dom.minidom.Element if event equals START_ELEMENT or END_ELEMENT or xml.dom.minidom.Text if event equals CHARACTERS. The current node does not contain information about its children, unless expandNode() is called.

expandNode(node)
Expands all children of node into node. Example: from xml.dom import pulldom

xml = '<title>Foo</title>
Some text
and more

 '
doc = pulldom.parseString(xml)
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'p':
        # Following statement only prints '
'
        print(node.toxml())
        doc.expandNode(node)
        # Following statement prints node with all its children '
Some text
and more

'
        print(node.toxml())

reset()


xml.dom.pulldom.default_bufsize
Default value for the bufsize parameter to parse(). The value of this variable can be changed before calling parse() and the new value will take effect.


class xml.dom.pulldom.DOMEventStream(stream, parser, bufsize)
 Deprecated since version 3.8: Support for sequence protocol is deprecated.
getEvent()
Return a tuple containing event and the current node as xml.dom.minidom.Document if event equals START_DOCUMENT, xml.dom.minidom.Element if event equals START_ELEMENT or END_ELEMENT or xml.dom.minidom.Text if event equals CHARACTERS. The current node does not contain information about its children, unless expandNode() is called.

expandNode(node)
Expands all children of node into node. Example: from xml.dom import pulldom

xml = '<title>Foo</title>
Some text
and more

 '
doc = pulldom.parseString(xml)
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'p':
        # Following statement only prints '
'
        print(node.toxml())
        doc.expandNode(node)
        # Following statement prints node with all its children '
Some text
and more

'
        print(node.toxml())

reset()


expandNode(node)
Expands all children of node into node. Example: from xml.dom import pulldom

xml = '<title>Foo</title>
Some text
and more

 '
doc = pulldom.parseString(xml)
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'p':
        # Following statement only prints '
'
        print(node.toxml())
        doc.expandNode(node)
        # Following statement prints node with all its children '
Some text
and more

'
        print(node.toxml())


getEvent()
Return a tuple containing event and the current node as xml.dom.minidom.Document if event equals START_DOCUMENT, xml.dom.minidom.Element if event equals START_ELEMENT or END_ELEMENT or xml.dom.minidom.Text if event equals CHARACTERS. The current node does not contain information about its children, unless expandNode() is called.


xml.dom.pulldom.parse(stream_or_string, parser=None, bufsize=None)
Return a DOMEventStream from the given input. stream_or_string may be either a file name, or a file-like object. parser, if given, must be an XMLReader 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.


xml.dom.pulldom.parseString(string, parser=None)
Return a DOMEventStream that represents the (Unicode) string.


class xml.dom.pulldom.PullDom(documentFactory=None)
Subclass of xml.sax.handler.ContentHandler.


class xml.dom.pulldom.SAX2DOM(documentFactory=None)
Subclass of xml.sax.handler.ContentHandler.


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).


exception xml.dom.SyntaxErr
Raised when an invalid or illegal string is specified.


Text.data
The content of the text node as a string.


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.


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).


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.XML_NAMESPACE
The namespace URI associated with the reserved prefix xml, as defined by Namespaces in XML (section 4).