ODF, Python and XML

Combine Python with the open format of ODF files to manipulate fine details.
The Bottom Layer: a Python/XML Script

My desktop distribution (SUSE 9.3) includes the packages python-doc-2.4-14 and python-doc-pdf-2.4-14. You also can get documentation from In either case, we want the Library Reference, which contains information on the Python XML libraries; they are described in the chapter on “Structured Markup Processing Tools” (currently Chapter 13).

Several modules are listed, and I noticed one labeled lightweight: xml.dom.minidom—Lightweight Document Object Model (DOM) implementation.

Lightweight sounded good to me. The library reference gives these examples:

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

So, it looks like parse can take a filename or a file object.

Exploring content.xml

Once we create a dom object, what can we do with it? One nice thing about Python is the interactive shell, which lets you try things out one at a time. Let's unpack the first example and look inside:

% mkdir TMP
% unzip -q -d TMP ex1.odt
% python
Python 2.4 (#1, Mar 22 2005, 21:42:42)
[GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license"
 for more information.
>>> import xml.dom.minidom
>>> dom=xml.dom.minidom.parse("TMP/content.xml")
>>> dir(dom)
[  --- a VERY long list, including ---
'childNodes', 'firstChild', 'nodeName', 'nodeValue', ...  ]
>>> len(dom.childNodes)
>>> c1=dom.firstChild
>>> len(c1.childNodes)
>>> for c2 in c1.childNodes: print c2.nodeName

Notice how Python's dir function tells what fields (including methods) are in the object. The childNodes field looks interesting, and indeed, it appears that the document has a tree structure. After a little more manual exploration, I discovered that text is contained in the data field of certain nodes. So, I coded up a naive script,

#!/usr/bin/python -tt
import xml.dom.minidom
import sys

def dprint(what):
   if DEBUG == 0: return
   sys.stderr.write(what + '\n')

def handle_xml_tree(aNode, depth):
   if aNode.hasChildNodes():
      for kid in aNode.childNodes:
         handle_xml_tree(kid, depth+1)
      if 'data' in dir(aNode):
         dprint(("depth=%d: " + % depth)

def doit(argv):
   doc = xml.dom.minidom.parse(argv[1])
   handle_xml_tree(doc, 0)
   # sys.stdout.write(doc.toxml('utf-8'))

if __name__ == "__main__":

The dprint routine prints debugging information on stderr; later we'll set DEBUG=0, and it'll be silent. Okay, let's try that on the content.xml above:

% ./ TMP/content.xml
depth=5: Turn all these
depth=6: "straight"
Traceback (most recent call last):
  File "./", line 24, in ?
  File "./", line 20, in doit
    handle_xml_tree(doc, 0)
  File "./", line 13, in handle_xml_tree
    handle_xml_tree(kid, depth+1)
  File "./", line 13, in handle_xml_tree
    handle_xml_tree(kid, depth+1)
  File "./", line 13, in handle_xml_tree
    handle_xml_tree(kid, depth+1)
  File "./", line 13, in handle_xml_tree
    handle_xml_tree(kid, depth+1)
  File "./", line 13, in handle_xml_tree
    handle_xml_tree(kid, depth+1)
  File "./", line 16, in handle_xml_tree
    dprint(("depth=%d: " + % depth)
  File "./", line 8, in dprint
    sys.stderr.write(what + '\n')
UnicodeEncodeError: 'ascii' codec can't encode character
u'\u201c' in position 22: ordinal not in range(128)

What's that error about? When trying to print that string on stderr, we hit a non-ASCII character—probably one of those curly quotes. A quick Web search gave this possible solution:

sys.stderr.write(what.encode('ascii', 'replace') + '\n')

It says that if a non-ASCII Unicode character appears, replace it with something in ASCII—an equivalent, or at least something printable.

Replacing line 8 with that yields this output:

% ./ TMP/content.xml
depth=5: Turn all these
depth=6: "straight"
depth=5:  quotes into ?nice? quotes

So the curly quotes were replaced with ? characters, which is fine for our debugging output. Note that the text doesn't necessarily all come at the same depth in the tree.

The document's structure also can be seen by typing the full filename of the content.xml file into a Firefox window (Figure 7). That's good for displaying the data; the point, however, is to change it!

Figure 7. Firefox presents the XML more clearly.


White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState