import xml.etree.cElementTree as ET # build a tree structure root = ET.Element("html") head = ET.SubElement(root, "head", attrib={"dir":"ltr"}) title = ET.SubElement(head, "title") title.text = "Page Title" body = ET.SubElement(root, "body") body.set("bgcolor", "#ffffff") body.text = "Hello, World!" # wrap it in an ElementTree instance, and save as XML tree = ET.ElementTree(root) tree.write("page.xhtml") # The above program is an example of a bug with cElementTree. # The file is identical to the example provided on the effbot.org # website (http://effbot.org/zone/element-index.htm#usage), # with just a couple of exceptions. # # Line 1 was adjusted to import the c version of the module, from the # appropriate location for Python 2.5 (xml.etree) # # Line 6 was adjusted to include an attribute by keyword (attrib=...). # # This program runs fine in the Python implementation of ElementTree, # but fails in the c implementation. (My understanding is that the c # implementation should be "plug compatible" with the python version.) # Error = """ Traceback (most recent call last): File "C:/PythonProjects/junk/cElementTreeTest.py", line 18, in tree.write("page.xhtml") File "C:\Python25\lib\xml\etree\ElementTree.py", line 663, in write self._write(file, self._root, encoding, {}) File "C:\Python25\lib\xml\etree\ElementTree.py", line 707, in _write self._write(file, n, encoding, namespaces) File "C:\Python25\lib\xml\etree\ElementTree.py", line 698, in _write _escape_attrib(v, encoding))) File "C:\Python25\lib\xml\etree\ElementTree.py", line 830, in _escape_attrib _raise_serialization_error(text) File "C:\Python25\lib\xml\etree\ElementTree.py", line 777, in _raise_serialization_error "cannot serialize %r (type %s)" % (text, type(text).__name__) TypeError: cannot serialize {'dir': 'ltr'} (type dict) """ # Workaround: remove the keyword "attrib=", and it works in both. print "ok"