Package lxml :: Module etree :: Class xmlfile
[hide private]
[frames] | no frames]

Class xmlfile

object --+
         |
        xmlfile
Known Subclasses:

xmlfile(self, output_file, encoding=None, compression=None, close=False, buffered=True)

A simple mechanism for incremental XML serialisation.

Usage example:

with xmlfile("somefile.xml", encoding='utf-8') as xf:
    xf.write_declaration(standalone=True)
    xf.write_doctype('<!DOCTYPE root SYSTEM "some.dtd">')

    # generate an element (the root element)
    with xf.element('root'):
         # write a complete Element into the open root element
         xf.write(etree.Element('test'))

         # generate and write more Elements, e.g. through iterparse
         for element in generate_some_elements():
             # serialise generated elements into the XML file
             xf.write(element)

         # or write multiple Elements or strings at once
         xf.write(etree.Element('start'), "text", etree.Element('end'))

If 'output_file' is a file(-like) object, passing close=True will close it when exiting the context manager. By default, it is left to the owner to do that. When a file path is used, lxml will take care of opening and closing the file itself. Also, when a compression level is set, lxml will deliberately close the file to make sure all data gets compressed and written.

Setting buffered=False will flush the output after each operation, such as opening or closing an xf.element() block or calling xf.write(). Alternatively, calling xf.flush() can be used to explicitly flush any pending output when buffering is enabled.

Instance Methods [hide private]
 
__enter__(...)
 
__exit__(...)
 
__init__(self, output_file, encoding=None, compression=None, close=False, buffered=True)
x.__init__(...) initializes x; see help(type(x)) for signature
a new object with type S, a subtype of T
__new__(T, S, ...)

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, output_file, encoding=None, compression=None, close=False, buffered=True)
(Constructor)

 
x.__init__(...) initializes x; see help(type(x)) for signature
Overrides: object.__init__

__new__(T, S, ...)

 
Returns: a new object with type S, a subtype of T
Overrides: object.__new__