A class to write well-formed and nicely indented XML.
Use like this:
w = XMLWriter(fh)
with w.tag('html'):
with w.tag('body'):
w.data('This is the content')
Which produces:
<html>
<body>
This is the content
</body>
</html>
Parameters: | file : writable file-like object. |
---|
Methods Summary
close(id) | Closes open elements, up to (and including) the element identified by the given identifier. |
comment(comment) | Adds a comment to the output stream. |
data(text) | Adds character data to the output stream. |
element(tag[, text, wrap, attrib]) | Adds an entire element. |
end([tag, indent, wrap]) | Closes the current element (opened by the most recent call to start). |
flush() | |
get_indentation() | Returns the number of indentation levels the file is currently in. |
get_indentation_spaces([offset]) | Returns a string of spaces that matches the current indentation level. |
object_attrs(obj, attrs) | Converts an object with a bunch of attributes on an object into a dictionary for use by the XMLWriter. |
start(tag[, attrib]) | Opens a new element. |
tag(*args, **kwds) | A convenience method for use with the with statement:: with writer.tag(‘foo’): writer.element(‘bar’) # </foo> is implicitly closed here Parameters are the same as to start. |
Methods Documentation
Closes open elements, up to (and including) the element identified by the given identifier.
Parameters: | id : int
|
---|
Adds a comment to the output stream.
Parameters: | comment : str
|
---|
Adds character data to the output stream.
Parameters: | text : str
|
---|
Adds an entire element. This is the same as calling start, data, and end in sequence. The text argument can be omitted.
Closes the current element (opened by the most recent call to start).
Parameters: | tag : str
|
---|
Returns the number of indentation levels the file is currently in.
Returns a string of spaces that matches the current indentation level.
Converts an object with a bunch of attributes on an object into a dictionary for use by the XMLWriter.
Parameters: | obj : object
attrs : sequence of str
|
---|---|
Returns: | attrs : dict
|
Opens a new element. Attributes can be given as keyword arguments, or as a string/string dictionary. The method returns an opaque identifier that can be passed to the close() method, to close all open elements up to and including this one.
Parameters: | tag : str
attrib : dict of str -> str
|
---|---|
Returns: | id : int
|
A convenience method for use with the with statement:
with writer.tag('foo'):
writer.element('bar')
# </foo> is implicitly closed here
Parameters are the same as to start.