Skip to content
-Smooth-E- edited this page Feb 15, 2023 · 3 revisions

Every element in the OpenDocument XML format is implemented as a Python class that derives from the Element class. The Element class has the following attributes:

  • nodeType - a code representing the type of the node.
  • parentNode - the parent of this node or None if it has not yet been added to the tree.
  • childNodes - a list of child nodes.
  • firstChild - the first child of this element.
  • lastChild - the last child of this element.
  • previousSibling - the node immediately preceding this node.
  • nextSibling - the node immediately following this node.

The Element class has the following methods:

  • addElement(element, check_grammar=True) – adds an element as a child to another element. It will check if the element can legally be a child, and raise an exception if not.
  • addText(text) – adds text to an element
  • addCDATA(cdata) – adds text, but treats it as CDATA.
  • setAttribute(attr, value, check_grammar=True) – adds or sets an attribute.
  • getAttribute(attr) – gets an attribute by name.
  • hasChildNodes() – tells whether this element has any children; text nodes, subelements of any kind.
  • insertBefore(newchild, refchild) – inserts the node newchild before the existing child node refchild.
  • appendChild(newchild) – adds the node newchild to the end of the list of children.
  • removeChild(oldchild) – removes the child node.
  • getElementsByType(class) – returns a list of all descendant elements of the given type.

The instantiation of an Element or a derived class is done the normal way you create an instance of a Python class. You must provide the required attributes. This can be done in two ways; as arguments, or as an attribute dictionary.

An example of arguments:

from odf.style import Style
h1style = Style(name="Heading 1", family="paragraph")

An example of attributes dictionary:

from odf.style import Style
h1style = Style(attributes={'name':'Heading 1', 'family':'paragraph'})

And finally, there are two convenient ways to add a text node. As text and cdata:

from odf import text

p = text.P(text=Hello World\n”)

s = text.Script(cdata=if (y < x) print 'less';”, language=JavaScript”)

There are so many elements, and some of them have the same name, that we have organised them in modules. To use a module you must first import it as a Python module. For instance, to create a paragraph do:

from odf import text
p = text.P(text=Hello World\n”)

The modules are:

  • anim
  • chart
  • config
  • dc
  • dr3d
  • draw
  • form
  • manifest
  • math
  • meta
  • number
  • office
  • presentation
  • script
  • style
  • svg
  • table
  • text
  • xforms

Besides these, there are also some convenience modules that implement often-used functionality:

  • userfield
  • teletype
  • easyliststyle
Clone this wiki locally