changeset 53:d071598a93ef

Tree support - Change module name
author Bastian Blank <bblank@thinkmo.de>
date Mon, 20 Jul 2009 11:08:47 +0200
parents 672b181a8ce0
children 6d2aaba7ac4d
files emeraldtree/ElementTree.py emeraldtree/tests/test_ElementTree.py emeraldtree/tests/test_tree.py emeraldtree/tree.py
diffstat 4 files changed, 1710 insertions(+), 1709 deletions(-) [+]
line wrap: on
line diff
--- a/emeraldtree/ElementTree.py	Mon Jul 20 11:07:06 2009 +0200
+++ b/emeraldtree/ElementTree.py	Mon Jul 20 11:08:47 2009 +0200
@@ -1,1436 +1,1 @@
-#
-# ElementTree
-# $Id: ElementTree.py 3276 2007-09-12 06:52:30Z fredrik $
-#
-# light-weight XML support for Python 2.2 and later.
-#
-# history:
-# 2001-10-20 fl   created (from various sources)
-# 2001-11-01 fl   return root from parse method
-# 2002-02-16 fl   sort attributes in lexical order
-# 2002-04-06 fl   TreeBuilder refactoring, added PythonDoc markup
-# 2002-05-01 fl   finished TreeBuilder refactoring
-# 2002-07-14 fl   added basic namespace support to ElementTree.write
-# 2002-07-25 fl   added QName attribute support
-# 2002-10-20 fl   fixed encoding in write
-# 2002-11-24 fl   changed default encoding to ascii; fixed attribute encoding
-# 2002-11-27 fl   accept file objects or file names for parse/write
-# 2002-12-04 fl   moved XMLTreeBuilder back to this module
-# 2003-01-11 fl   fixed entity encoding glitch for us-ascii
-# 2003-02-13 fl   added XML literal factory
-# 2003-02-21 fl   added ProcessingInstruction/PI factory
-# 2003-05-11 fl   added tostring/fromstring helpers
-# 2003-05-26 fl   added ElementPath support
-# 2003-07-05 fl   added makeelement factory method
-# 2003-07-28 fl   added more well-known namespace prefixes
-# 2003-08-15 fl   fixed typo in ElementTree.findtext (Thomas Dartsch)
-# 2003-09-04 fl   fall back on emulator if ElementPath is not installed
-# 2003-10-31 fl   markup updates
-# 2003-11-15 fl   fixed nested namespace bug
-# 2004-03-28 fl   added XMLID helper
-# 2004-06-02 fl   added default support to findtext
-# 2004-06-08 fl   fixed encoding of non-ascii element/attribute names
-# 2004-08-23 fl   take advantage of post-2.1 expat features
-# 2004-09-03 fl   made Element class visible; removed factory
-# 2005-02-01 fl   added iterparse implementation
-# 2005-03-02 fl   fixed iterparse support for pre-2.2 versions
-# 2005-11-12 fl   added tostringlist/fromstringlist helpers
-# 2006-07-05 fl   merged in selected changes from the 1.3 sandbox
-# 2006-07-05 fl   removed support for 2.1 and earlier
-# 2007-06-21 fl   added deprecation/future warnings
-# 2007-08-25 fl   added doctype hook, added parser version attribute etc
-# 2007-08-26 fl   added new serializer code (better namespace handling, etc)
-# 2007-08-27 fl   warn for broken /tag searches on tree level
-# 2007-09-02 fl   added html/text methods to serializer (experimental)
-# 2007-09-05 fl   added method argument to tostring/tostringlist
-# 2007-09-06 fl   improved error handling
-#
-# Copyright (c) 1999-2007 by Fredrik Lundh.  All rights reserved.
-#
-# fredrik@pythonware.com
-# http://www.pythonware.com
-#
-# --------------------------------------------------------------------
-# The ElementTree toolkit is
-#
-# Copyright (c) 1999-2007 by Fredrik Lundh
-#               2008 Bastian Blank <bblank@thinkmo.de>
-#
-# By obtaining, using, and/or copying this software and/or its
-# associated documentation, you agree that you have read, understood,
-# and will comply with the following terms and conditions:
-#
-# Permission to use, copy, modify, and distribute this software and
-# its associated documentation for any purpose and without fee is
-# hereby granted, provided that the above copyright notice appears in
-# all copies, and that both that copyright notice and this permission
-# notice appear in supporting documentation, and that the name of
-# Secret Labs AB or the author not be used in advertising or publicity
-# pertaining to distribution of the software without specific, written
-# prior permission.
-#
-# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
-# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
-# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
-# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
-# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
-# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
-# OF THIS SOFTWARE.
-# --------------------------------------------------------------------
-
-from __future__ import generators
-
-__all__ = [
-    # public symbols
-    "Comment",
-    "dump",
-    "Element", "ElementTree",
-    "fromstring", "fromstringlist",
-    "iterparse",
-    "Node",
-    "parse", "ParseError",
-    "PI", "ProcessingInstruction",
-    "QName",
-    "SubElement",
-    "tostring", "tostringlist",
-    "TreeBuilder",
-    "XML",
-    "XMLParser",
-    ]
-
-##
-# The <b>Element</b> type is a flexible container object, designed to
-# store hierarchical data structures in memory. The type can be
-# described as a cross between a list and a dictionary.
-# <p>
-# Each element has a number of properties associated with it:
-# <ul>
-# <li>a <i>tag</i>. This is a string identifying what kind of data
-# this element represents (the element type, in other words).</li>
-# <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
-# <li>a <i>text</i> string.</li>
-# <li>an optional <i>tail</i> string.</li>
-# <li>a number of <i>child elements</i>, stored in a Python sequence</li>
-# </ul>
-#
-# To create an element instance, use the {@link #Element} constructor
-# or the {@link #SubElement} factory function.
-# <p>
-# The {@link #ElementTree} class can be used to wrap an element
-# structure, and convert it from and to XML.
-##
-
-import ElementPath
-
-class ParseError(SyntaxError):
-    pass
-
-# --------------------------------------------------------------------
-
-class Node(object):
-    """
-    Node class.
-    """
-
-##
-# Element class.  This class defines the Element interface, and
-# provides a reference implementation of this interface.
-# <p>
-# The element name, attribute names, and attribute values can be
-# either 8-bit ASCII strings or Unicode strings.
-#
-# @param tag The element name.
-# @param attrib An optional dictionary, containing element attributes.
-# @param **extra Additional attributes, given as keyword arguments.
-# @see Element
-# @see SubElement
-# @see Comment
-# @see ProcessingInstruction
-
-class Element(Node):
-    # <tag attrib>text<child/>...</tag>tail
-
-    ##
-    # (Attribute) Element tag.
-
-    tag = None
-
-    ##
-    # (Attribute) Element attribute dictionary.  Where possible, use
-    # {@link #Element.get},
-    # {@link #Element.set},
-    # {@link #Element.keys}, and
-    # {@link #Element.items} to access
-    # element attributes.
-
-    attrib = None
-
-    ##
-    # (Attribute) Text before first subelement.  This is either a
-    # string or the value None, if there was no text.
-
-    @property
-    def text(self):
-        if len(self) and isinstance(self[0], basestring):
-            return self[0]
-
-    ##
-    # (Attribute) Text after this element's end tag, but before the
-    # next sibling element's start tag.  This is either a string or
-    # the value None, if there was no text.
-
-    @property
-    def tail(self):
-        raise RuntimeError('The tail argument is not supported')
-
-    def __init__(self, tag, attrib=None, children=(), **extra):
-        if attrib:
-            if isinstance(attrib, dict):
-                attrib = attrib.copy()
-            else:
-                raise TypeError('attrib')
-        else:
-            attrib = {}
-        attrib.update(extra)
-        self.tag = tag
-        self.attrib = attrib
-        self._children = [self._check_node(i) for i in children]
-
-    def __repr__(self):
-        return "<Element %s at %x>" % (repr(self.tag), id(self))
-
-    ##
-    # Returns the number of subelements.
-    #
-    # @return The number of subelements.
-
-    def __len__(self):
-        return len(self._children)
-
-    def __nonzero__(self):
-        return True
-
-    ##
-    # Returns the given subelement.
-    #
-    # @param index What subelement to return.
-    # @return The given subelement.
-    # @exception IndexError If the given element does not exist.
-
-    def __getitem__(self, index):
-        return self._children.__getitem__(index)
-
-    ##
-    # Replaces the given subelement.
-    #
-    # @param index What subelement to replace.
-    # @param element The new element value.
-    # @exception IndexError If the given element does not exist.
-    # @exception AssertionError If element is not a valid object.
-
-    def __setitem__(self, index, element):
-        if isinstance(index, slice):
-            element = [self._check_node(i) for i in element]
-        else:
-            element = self._check_node(element)
-        self._children.__setitem__(index, element)
-
-    ##
-    # Deletes the given subelement.
-    #
-    # @param index What subelement to delete.
-    # @exception IndexError If the given element does not exist.
-
-    def __delitem__(self, index):
-        self._children.__delitem__(index)
-
-    @staticmethod
-    def _check_node(node):
-        if isinstance(node, (Node, unicode)):
-            return node
-        if isinstance(node, str):
-            return unicode(node)
-        raise TypeError
-
-    ##
-    # Adds a subelement to the end of this element.
-    #
-    # @param element The element to add.
-    # @exception AssertionError If a sequence member is not a valid object.
-
-    def append(self, element):
-        element = self._check_node(element)
-        self._children.append(element)
-
-    ##
-    # Appends subelements from a sequence.
-    #
-    # @param elements A sequence object with zero or more elements.
-    # @exception AssertionError If a subelement is not a valid object.
-    # @since 1.3
-
-    def extend(self, elements):
-        elements = [self._check_node(i) for i in elements]
-        self._children.extend(elements)
-
-    ##
-    # Inserts a subelement at the given position in this element.
-    #
-    # @param index Where to insert the new subelement.
-    # @exception AssertionError If the element is not a valid object.
-
-    def insert(self, index, element):
-        element = self._check_node(element)
-        self._children.insert(index, element)
-
-    ##
-    # Removes a matching subelement.  Unlike the <b>find</b> methods,
-    # this method compares elements based on identity, not on tag
-    # value or contents.
-    #
-    # @param element What element to remove.
-    # @exception ValueError If a matching element could not be found.
-    # @exception AssertionError If the element is not a valid object.
-
-    def remove(self, element):
-        self._children.remove(element)
-
-    ##
-    # Finds the first matching subelement, by tag name or path.
-    #
-    # @param path What element to look for.
-    # @return The first matching element, or None if no element was found.
-    # @defreturn Element or None
-
-    def find(self, path):
-        return ElementPath.find(self, path)
-
-    ##
-    # Finds text for the first matching subelement, by tag name or path.
-    #
-    # @param path What element to look for.
-    # @param default What to return if the element was not found.
-    # @return The text content of the first matching element, or the
-    #     default value no element was found.  Note that if the element
-    #     has is found, but has no text content, this method returns an
-    #     empty string.
-    # @defreturn string
-
-    def findtext(self, path, default=None):
-        return ElementPath.findtext(self, path, default)
-
-    ##
-    # Finds all matching subelements, by tag name or path.
-    #
-    # @param path What element to look for.
-    # @return A list or iterator containing all matching elements,
-    #    in document order.
-    # @defreturn list of Element instances
-
-    def findall(self, path):
-        return ElementPath.findall(self, path)
-
-    ##
-    # Resets an element.  This function removes all subelements, clears
-    # all attributes, and sets the text and tail attributes to None.
-
-    def clear(self):
-        self.attrib.clear()
-        self._children = []
-
-    ##
-    # Gets an element attribute.
-    #
-    # @param key What attribute to look for.
-    # @param default What to return if the attribute was not found.
-    # @return The attribute value, or the default value, if the
-    #     attribute was not found.
-
-    def get(self, key, default=None):
-        return self.attrib.get(key, default)
-
-    ##
-    # Sets an element attribute.
-    #
-    # @param key What attribute to set.
-    # @param value The attribute value.
-
-    def set(self, key, value):
-        self.attrib[key] = value
-
-    ##
-    # Gets a list of attribute names.  The names are returned in an
-    # arbitrary order (just like for an ordinary Python dictionary).
-    #
-    # @return A list of element attribute names.
-    # @defreturn list of strings
-
-    def keys(self):
-        return self.attrib.keys()
-
-    ##
-    # Gets element attributes, as a sequence.  The attributes are
-    # returned in an arbitrary order.
-    #
-    # @return A list of (name, value) tuples for all attributes.
-    # @defreturn list of (string, string) tuples
-
-    def items(self):
-        return self.attrib.items()
-
-    def __iter__(self):
-        """
-        Creates a element iterator.  The iterator loops over all children.
-        """
-        return self._children.__iter__()
-
-    ##
-    # Creates a tree iterator.  The iterator loops over this element
-    # and all subelements, in document order, and returns all elements
-    # with a matching tag.
-    # <p>
-    # If the tree structure is modified during iteration, new or removed
-    # elements may or may not be included.  To get a stable set, use the
-    # list() function on the iterator, and loop over the resulting list.
-    #
-    # @param tag What tags to look for (default is to return all elements).
-    # @return An iterator containing all the matching elements.
-    # @defreturn iterator
-
-    def iter(self, tag=None):
-        if tag == "*":
-            tag = None
-        if tag is None or self.tag == tag:
-            yield self
-        for e in self._children:
-            if isinstance(e, Element):
-                for e in e.iter(tag):
-                    yield e
-            else:
-                yield e
-
-    ##
-    # Creates a text iterator.  The iterator loops over this element
-    # and all subelements, in document order, and returns all inner
-    # text.
-    #
-    # @return An iterator containing all inner text.
-    # @defreturn iterator
-
-    def itertext(self):
-        for e in self:
-            if isinstance(e, Element):
-                for s in e.itertext():
-                    yield s
-            elif isinstance(e, basestring):
-                yield e
-
-##
-# Subelement factory.  This function creates an element instance, and
-# appends it to an existing element.
-# <p>
-# The element name, attribute names, and attribute values can be
-# either 8-bit ASCII strings or Unicode strings.
-#
-# @param parent The parent element.
-# @param tag The subelement name.
-# @param attrib An optional dictionary, containing element attributes.
-# @param **extra Additional attributes, given as keyword arguments.
-# @return An element instance.
-# @defreturn Element
-
-def SubElement(parent, tag, attrib=None, **extra):
-    attrib = attrib and attrib.copy() or {}
-    attrib.update(extra)
-    element = parent.makeelement(tag, attrib)
-    parent.append(element)
-    return element
-
-##
-# Comment element factory.  This factory function creates a special
-# element that will be serialized as an XML comment by the standard
-# serializer.
-# <p>
-# The comment string can be either an 8-bit ASCII string or a Unicode
-# string.
-#
-# @param text A string containing the comment string.
-# @return An element instance, representing a comment.
-# @defreturn Element
-
-class Comment(Node):
-    def __init__(self, text = None):
-        self.text = text
-
-##
-# PI element factory.  This factory function creates a special element
-# that will be serialized as an XML processing instruction by the standard
-# serializer.
-#
-# @param target A string containing the PI target.
-# @param text A string containing the PI contents, if any.
-# @return An element instance, representing a PI.
-# @defreturn Element
-
-class ProcessingInstruction(Node):
-    def __init__(self, target, text = None):
-        self.target, self.text = target, text
-
-PI = ProcessingInstruction
-
-##
-# QName wrapper.  This can be used to wrap a QName attribute value, in
-# order to get proper namespace handling on output.
-#
-# @return An opaque object, representing the QName.
-
-class QName(unicode):
-    __slots__ = 'name', 'uri'
-
-    def __new__(cls, name, uri=None):
-        text = name = unicode(name)
-
-        if name[0] == '{':
-            if uri is not None:
-                raise ValueError
-            i = name.find('}')
-            if i == -1:
-                raise ValueError
-            uri = name[1:i]
-            name = name[i + 1:]
-
-        if uri is not None:
-            uri = unicode(uri)
-            text = '{' + uri + '}' + name
-
-        ret = unicode.__new__(cls, text)
-        unicode.__setattr__(ret, 'name', name)
-        unicode.__setattr__(ret, 'uri', uri)
-
-        return ret
-
-    def __getnewargs__(self):
-        return self.name, self.uri
-
-    def __getstate__(self):
-        pass
-
-    def __repr__(self):
-        return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.uri)
-
-    def __setattr__(self, key, value):
-        raise AttributeError('read-only')
-
-    def copy(self):
-        return self.__class__(self.name, self.uri)
-
-    @property
-    def text(self):
-        return self
-
-# --------------------------------------------------------------------
-
-##
-# ElementTree wrapper class.  This class represents an entire element
-# hierarchy, and adds some extra support for serialization to and from
-# standard XML.
-#
-# @param element Optional root element.
-# @keyparam file Optional file handle or file name.  If given, the
-#     tree is initialized with the contents of this XML file.
-
-class ElementTree(object):
-
-    def __init__(self, element=None, file=None):
-        assert element is None or isinstance(element, Node)
-        self._root = element # first node
-        if file:
-            self.parse(file)
-
-    ##
-    # Gets the root element for this tree.
-    #
-    # @return An element instance.
-    # @defreturn Element
-
-    def getroot(self):
-        return self._root
-
-    ##
-    # Loads an external XML document into this element tree.
-    #
-    # @param source A file name or file object.
-    # @keyparam parser An optional parser instance.  If not given, the
-    #     standard {@link XMLParser} parser is used.
-    # @return The document root element.
-    # @defreturn Element
-
-    def parse(self, source, parser=None):
-        if not hasattr(source, "read"):
-            source = open(source, "rb")
-        if not parser:
-            parser = XMLParser(target=TreeBuilder())
-        while 1:
-            data = source.read(32768)
-            if not data:
-                break
-            parser.feed(data)
-        self._root = parser.close()
-        return self._root
-
-    ##
-    # Creates a tree iterator for the root element.  The iterator loops
-    # over all elements in this tree, in document order.
-    #
-    # @param tag What tags to look for (default is to return all elements)
-    # @return An iterator.
-    # @defreturn iterator
-
-    def iter(self, tag=None):
-        assert self._root is not None
-        return self._root.iter(tag)
-
-    getiterator = iter
-
-    ##
-    # Finds the first toplevel element with given tag.
-    # Same as getroot().find(path).
-    #
-    # @param path What element to look for.
-    # @return The first matching element, or None if no element was found.
-    # @defreturn Element or None
-
-    def find(self, path):
-        assert self._root is not None
-        if path[:1] == "/":
-            path = "." + path
-            import warnings
-            warnings.warn(
-                "This search is broken in 1.3 and earlier; if you rely "
-                "on the current behaviour, change it to %r" % path,
-                FutureWarning
-                )
-        return self._root.find(path)
-
-    ##
-    # Finds the element text for the first toplevel element with given
-    # tag.  Same as getroot().findtext(path).
-    #
-    # @param path What toplevel element to look for.
-    # @param default What to return if the element was not found.
-    # @return The text content of the first matching element, or the
-    #     default value no element was found.  Note that if the element
-    #     has is found, but has no text content, this method returns an
-    #     empty string.
-    # @defreturn string
-
-    def findtext(self, path, default=None):
-        assert self._root is not None
-        if path[:1] == "/":
-            path = "." + path
-            import warnings
-            warnings.warn(
-                "This search is broken in 1.3 and earlier; if you rely "
-                "on the current behaviour, change it to %r" % path,
-                FutureWarning
-                )
-        return self._root.findtext(path, default)
-
-    ##
-    # Finds all toplevel elements with the given tag.
-    # Same as getroot().findall(path).
-    #
-    # @param path What element to look for.
-    # @return A list or iterator containing all matching elements,
-    #    in document order.
-    # @defreturn list of Element instances
-
-    def findall(self, path):
-        assert self._root is not None
-        if path[:1] == "/":
-            path = "." + path
-            import warnings
-            warnings.warn(
-                "This search is broken in 1.3 and earlier; if you rely "
-                "on the current behaviour, change it to %r" % path,
-                FutureWarning
-                )
-        return self._root.findall(path)
-
-    ##
-    # Writes the element tree to a file, as XML.
-    #
-    # @param file A file name, or a file object opened for writing.
-    # @keyparam encoding Optional output encoding (default is US-ASCII).
-    # @keyparam method Optional output method ("xml" or "html"; default
-    #     is "xml".
-    # @keyparam xml_declaration Controls if an XML declaration should
-    #     be added to the file.  Use False for never, True for always,
-    #     None for only if not US-ASCII or UTF-8.  None is default.
-
-    def write(self, file,
-              # keyword arguments
-              encoding="us-ascii",
-              xml_declaration=None,
-              default_namespace=None,
-              method=None,
-              namespaces=None):
-        assert self._root is not None
-        if not hasattr(file, "write"):
-            file = open(file, "wb")
-        write = file.write
-        if not method:
-            method = "xml"
-        elif method == 'html':
-            default_namespace = "http://www.w3.org/1999/xhtml"
-        if not encoding:
-            encoding = "us-ascii"
-        elif xml_declaration or (xml_declaration is None and
-                                 encoding not in ("utf-8", "us-ascii")):
-            write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
-        if method == "text":
-            _serialize_text(write, self._root, encoding)
-        else:
-            qnames, namespaces = _namespaces(
-                self._root, encoding, default_namespace, namespaces
-                )
-            if method == "xml":
-                _serialize_xml(
-                    write, self._root, encoding, qnames, namespaces
-                    )
-            elif method == "html":
-                _serialize_html(
-                    write, self._root, encoding, qnames, namespaces
-                    )
-            else:
-                raise ValueError("unknown method %r" % method)
-
-# --------------------------------------------------------------------
-# serialization support
-
-def _namespaces(elem, encoding, default_namespace, namespaces):
-    # identify namespaces used in this tree
-
-    # maps qnames to *encoded* prefix:local names
-    qnames = {None: None}
-
-    # maps uri:s to prefixes
-    candidate_namespaces = _namespace_map.copy()
-    if namespaces:
-        candidate_namespaces.update(namespaces)
-    if default_namespace:
-        candidate_namespaces[default_namespace] = ""
-    used_namespaces = {}
-
-    def encode(text):
-        return text.encode(encoding)
-
-    def add_qname(qname):
-        if qname in qnames:
-            return
-
-        # calculate serialized qname representation
-        try:
-            if qname.uri is not None:
-                uri = qname.uri
-                prefix = used_namespaces.get(uri, None)
-                if prefix is None:
-                    prefix = candidate_namespaces.get(uri, None)
-                    if prefix is None:
-                        prefix = "ns%d" % len(used_namespaces)
-                    if prefix != "xml":
-                        used_namespaces[uri] = prefix
-                if prefix:
-                    qnames[qname] = encode("%s:%s" % (prefix, qname.name))
-                else:
-                    qnames[qname] = encode(qname.name)
-            else:
-                # XXX: What happens with undefined namespace?
-                qnames[qname] = encode(qname.name)
-        except TypeError:
-            _raise_serialization_error(qname)
-
-    # populate qname and namespaces table
-    if isinstance(elem, Element):
-        for elem in elem.iter():
-            if isinstance(elem, Element):
-                tag = elem.tag
-                if isinstance(tag, QName):
-                    add_qname(tag)
-                elif isinstance(tag, basestring):
-                    add_qname(QName(tag))
-                elif tag is not None:
-                    _raise_serialization_error(tag)
-
-                for key in elem.keys():
-                    if isinstance(key, QName):
-                        add_qname(key)
-                    elif isinstance(key, basestring):
-                        add_qname(QName(key))
-                    elif key is not None:
-                        _raise_serialization_error(key)
-
-    return qnames, used_namespaces
-
-def _serialize_xml(write, elem, encoding, qnames, namespaces):
-    if isinstance(elem, Element):
-        tag = qnames[elem.tag]
-
-        if tag is not None:
-            write("<" + tag)
-
-            if elem.attrib:
-                items = elem.attrib.items()
-                items.sort(key=lambda x: x[0])
-                for k, v in items:
-                    k = qnames[k]
-                    if isinstance(v, QName):
-                        v = qnames[v]
-                    else:
-                        v = _escape_attrib(v, encoding)
-                    write(' ' + k + '="' + v + '"')
-            if namespaces:
-                items = namespaces.items()
-                items.sort(key=lambda x: x[1]) # sort on prefix
-                for v, k in items:
-                    if k:
-                        k = ":" + k
-                    write(" xmlns%s=\"%s\"" % (
-                        k.encode(encoding),
-                        _escape_attrib(v, encoding)
-                        ))
-            if len(elem):
-                write(">")
-                for e in elem:
-                    _serialize_xml(write, e, encoding, qnames, None)
-                write("</" + tag + ">")
-            else:
-                write(" />")
-
-        else:
-            for e in elem:
-                _serialize_xml(write, e, encoding, qnames, None)
-
-    elif isinstance(elem, Comment):
-        write("<!--%s-->" % _escape_cdata(elem.text, encoding))
-
-    elif isinstance(elem, ProcessingInstruction):
-        text = _escape_cdata(elem.target, encoding)
-        if elem.text is not None:
-            text += ' ' + _escape_cdata(elem.text, encoding)
-        write("<?%s?>" % text)
-
-    else:
-        write(_escape_cdata(unicode(elem), encoding))
-
-HTML_EMPTY = set(("area", "base", "basefont", "br", "col", "frame", "hr",
-                  "img", "input", "isindex", "link", "meta" "param"))
-
-def _serialize_html(write, elem, encoding, qnames, namespaces):
-    if isinstance(elem, Element):
-        tag = qnames[elem.tag]
-
-        if tag is not None:
-            write("<" + tag)
-
-            if elem.attrib:
-                items = elem.attrib.items()
-                items.sort(key=lambda x: x[0])
-                for k, v in items:
-                    k = qnames[k]
-                    if isinstance(v, QName):
-                        v = qnames[v]
-                    else:
-                        v = _escape_attrib(v, encoding)
-                    # FIXME: handle boolean attributes
-                    write(' ' + k + '="' + v + '"')
-            if namespaces:
-                items = namespaces.items()
-                items.sort(key=lambda x: x[1]) # sort on prefix
-                for v, k in items:
-                    if k:
-                        k = ":" + k
-                    write(" xmlns%s=\"%s\"" % (
-                        k.encode(encoding),
-                        _escape_attrib(v, encoding)
-                        ))
-            write(">")
-
-            if tag.lower() in ('script', 'style'):
-                write(_encode(''.join(elem.itertext()), encoding))
-            else:
-                for e in elem:
-                    _serialize_html(write, e, encoding, qnames, None)
-
-            if tag not in HTML_EMPTY:
-                write("</" + tag + ">")
-
-        else:
-            for e in elem:
-                _serialize_html(write, e, encoding, qnames, None)
-
-    elif isinstance(elem, Comment):
-        write("<!--%s-->" % _escape_cdata(elem.text, encoding))
-
-    elif isinstance(elem, ProcessingInstruction):
-        text = _escape_cdata(elem.target, encoding)
-        if elem.text is not None:
-            text += ' ' + _escape_cdata(elem.text, encoding)
-        write("<?%s?>" % text)
-
-    else:
-        write(_escape_cdata(elem, encoding))
-
-def _serialize_text(write, elem, encoding):
-    for part in elem.itertext():
-        write(part.encode(encoding))
-
-##
-# Registers a namespace prefix.  The registry is global, and any
-# existing mapping for either the given prefix or the namespace URI
-# will be removed.
-#
-# @param prefix Namespace prefix.
-# @param uri Namespace uri.  Tags and attributes in this namespace
-#     will be serialized with the given prefix, if at all possible.
-# @raise ValueError If the prefix is reserved, or is otherwise
-#     invalid.
-
-def register_namespace(prefix, uri):
-    import re
-    if re.match("ns\d+$", prefix):
-        raise ValueError("Prefix format reserved for internal use")
-    for k, v in _namespace_map.items():
-        if k == uri or v == prefix:
-            del _namespace_map[k]
-    _namespace_map[uri] = prefix
-
-_namespace_map = {
-    # "well-known" namespace prefixes
-    "http://www.w3.org/XML/1998/namespace": "xml",
-    "http://www.w3.org/1999/xhtml": "html",
-    "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
-    "http://schemas.xmlsoap.org/wsdl/": "wsdl",
-    # xml schema
-    "http://www.w3.org/2001/XMLSchema": "xs",
-    "http://www.w3.org/2001/XMLSchema-instance": "xsi",
-    # dublic core
-    "http://purl.org/dc/elements/1.1/": "dc",
-}
-
-def _raise_serialization_error(text):
-    raise TypeError(
-        "cannot serialize %r (type %s)" % (text, type(text).__name__)
-        )
-
-def _encode(text, encoding):
-    try:
-        return text.encode(encoding, "xmlcharrefreplace")
-    except (TypeError, AttributeError):
-        _raise_serialization_error(text)
-
-def _escape_cdata(text, encoding):
-    # escape character data
-    try:
-        # it's worth avoiding do-nothing calls for strings that are
-        # shorter than 500 character, or so.  assume that's, by far,
-        # the most common case in most applications.
-        if "&" in text:
-            text = text.replace("&", "&amp;")
-        if "<" in text:
-            text = text.replace("<", "&lt;")
-        if ">" in text:
-            text = text.replace(">", "&gt;")
-        return text.encode(encoding, "xmlcharrefreplace")
-    except (TypeError, AttributeError):
-        _raise_serialization_error(text)
-
-def _escape_attrib(text, encoding):
-    # escape attribute value
-    try:
-        if "&" in text:
-            text = text.replace("&", "&amp;")
-        if "<" in text:
-            text = text.replace("<", "&lt;")
-        if ">" in text:
-            text = text.replace(">", "&gt;")
-        if "\"" in text:
-            text = text.replace("\"", "&quot;")
-        if "\n" in text:
-            text = text.replace("\n", "&#10;")
-        return text.encode(encoding, "xmlcharrefreplace")
-    except (TypeError, AttributeError):
-        _raise_serialization_error(text)
-
-# --------------------------------------------------------------------
-
-##
-# Generates a string representation of an XML element, including all
-# subelements.
-#
-# @param element An Element instance.
-# @return An encoded string containing the XML data.
-# @defreturn string
-
-def tostring(element, encoding=None, method=None):
-    class dummy:
-        pass
-    data = []
-    file = dummy()
-    file.write = data.append
-    ElementTree(element).write(file, encoding, method=method)
-    return "".join(data)
-
-##
-# Generates a string representation of an XML element, including all
-# subelements.  The string is returned as a sequence of string fragments.
-#
-# @param element An Element instance.
-# @return A sequence object containing the XML data.
-# @defreturn sequence
-# @since 1.3
-
-def tostringlist(element, encoding=None):
-    class dummy:
-        pass
-    data = []
-    file = dummy()
-    file.write = data.append
-    ElementTree(element).write(file, encoding)
-    # FIXME: merge small fragments into larger parts
-    return data
-
-##
-# Writes an element tree or element structure to sys.stdout.  This
-# function should be used for debugging only.
-# <p>
-# The exact output format is implementation dependent.  In this
-# version, it's written as an ordinary XML file.
-#
-# @param elem An element tree or an individual element.
-
-def dump(elem):
-    # debugging
-    import sys
-    if not isinstance(elem, ElementTree):
-        elem = ElementTree(elem)
-    elem.write(sys.stdout)
-    tail = elem.getroot().tail
-    if not tail or tail[-1] != "\n":
-        sys.stdout.write("\n")
-
-# --------------------------------------------------------------------
-# parsing
-
-##
-# Parses an XML document into an element tree.
-#
-# @param source A filename or file object containing XML data.
-# @param parser An optional parser instance.  If not given, the
-#     standard {@link XMLParser} parser is used.
-# @return An ElementTree instance
-
-def parse(source, parser=None):
-    tree = ElementTree()
-    tree.parse(source, parser)
-    return tree
-
-##
-# Parses an XML document into an element tree incrementally, and reports
-# what's going on to the user.
-#
-# @param source A filename or file object containing XML data.
-# @param events A list of events to report back.  If omitted, only "end"
-#     events are reported.
-# @param parser An optional parser instance.  If not given, the
-#     standard {@link XMLParser} parser is used.
-# @return A (event, elem) iterator.
-
-def iterparse(source, events=None, parser=None):
-    if not hasattr(source, "read"):
-        source = open(source, "rb")
-    if not parser:
-        parser = XMLParser(target=TreeBuilder())
-    return _IterParseIterator(source, events, parser)
-
-class _IterParseIterator(object):
-
-    def __init__(self, source, events, parser):
-        self._file = source
-        self._events = []
-        self._index = 0
-        self.root = self._root = None
-        self._parser = parser
-        # wire up the parser for event reporting
-        parser = self._parser._parser
-        append = self._events.append
-        if events is None:
-            events = ["end"]
-        for event in events:
-            if event == "start":
-                try:
-                    parser.ordered_attributes = 1
-                    parser.specified_attributes = 1
-                    def handler(tag, attrib_in, event=event, append=append,
-                                start=self._parser._start_list):
-                        append((event, start(tag, attrib_in)))
-                    parser.StartElementHandler = handler
-                except AttributeError:
-                    def handler(tag, attrib_in, event=event, append=append,
-                                start=self._parser._start):
-                        append((event, start(tag, attrib_in)))
-                    parser.StartElementHandler = handler
-            elif event == "end":
-                def handler(tag, event=event, append=append,
-                            end=self._parser._end):
-                    append((event, end(tag)))
-                parser.EndElementHandler = handler
-            elif event == "start-ns":
-                def handler(prefix, uri, event=event, append=append):
-                    try:
-                        uri = uri.encode("ascii")
-                    except UnicodeError:
-                        pass
-                    append((event, (prefix or "", uri)))
-                parser.StartNamespaceDeclHandler = handler
-            elif event == "end-ns":
-                def handler(prefix, event=event, append=append):
-                    append((event, None))
-                parser.EndNamespaceDeclHandler = handler
-
-    def next(self):
-        while 1:
-            try:
-                item = self._events[self._index]
-            except IndexError:
-                if self._parser is None:
-                    self.root = self._root
-                    raise StopIteration
-                # load event buffer
-                del self._events[:]
-                self._index = 0
-                data = self._file.read(16384)
-                if data:
-                    self._parser.feed(data)
-                else:
-                    self._root = self._parser.close()
-                    self._parser = None
-            else:
-                self._index = self._index + 1
-                return item
-
-    def __iter__(self):
-        return self
-
-##
-# Parses an XML document from a string constant.  This function can
-# be used to embed "XML literals" in Python code.
-#
-# @param source A string containing XML data.
-# @param parser An optional parser instance.  If not given, the
-#     standard {@link XMLParser} parser is used.
-# @return An Element instance.
-# @defreturn Element
-
-def XML(text, parser=None):
-    if not parser:
-        parser = XMLParser(target=TreeBuilder())
-    parser.feed(text)
-    return parser.close()
-
-##
-# Parses an XML document from a string constant, and also returns
-# a dictionary which maps from element id:s to elements.
-#
-# @param source A string containing XML data.
-# @param parser An optional parser instance.  If not given, the
-#     standard {@link XMLParser} parser is used.
-# @return A tuple containing an Element instance and a dictionary.
-# @defreturn (Element, dictionary)
-
-def XMLID(text, parser=None):
-    if not parser:
-        parser = XMLParser(target=TreeBuilder())
-    parser.feed(text)
-    tree = parser.close()
-    ids = {}
-    for elem in tree.getiterator():
-        id = elem.get("id")
-        if id:
-            ids[id] = elem
-    return tree, ids
-
-##
-# Parses an XML document from a string constant.  Same as {@link #XML}.
-#
-# @def fromstring(text)
-# @param source A string containing XML data.
-# @return An Element instance.
-# @defreturn Element
-
-fromstring = XML
-
-##
-# Parses an XML document from a sequence of string fragments.
-#
-# @param sequence A list or other sequence containing XML data fragments.
-# @param parser An optional parser instance.  If not given, the
-#     standard {@link XMLParser} parser is used.
-# @return An Element instance.
-# @defreturn Element
-# @since 1.3
-
-def fromstringlist(sequence, parser=None):
-    if not parser:
-        parser = XMLParser(target=TreeBuilder())
-    for text in sequence:
-        parser.feed(text)
-    return parser.close()
-
-# --------------------------------------------------------------------
-
-##
-# Generic element structure builder.  This builder converts a sequence
-# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
-# #TreeBuilder.end} method calls to a well-formed element structure.
-# <p>
-# You can use this class to build an element structure using a custom XML
-# parser, or a parser for some other XML-like format.
-#
-# @param element_factory Optional element factory.  This factory
-#    is called to create new Element instances, as necessary.
-
-class TreeBuilder(object):
-
-    def __init__(self, element_factory=None):
-        self._data = [] # data collector
-        self._elem = [] # element stack
-        self._last = None # last element
-        if element_factory is None:
-            element_factory = Element
-        self._factory = element_factory
-
-    ##
-    # Flushes the builder buffers, and returns the toplevel document
-    # element.
-    #
-    # @return An Element instance.
-    # @defreturn Element
-
-    def close(self):
-        assert len(self._elem) == 0, "missing end tags"
-        assert self._last is not None, "missing toplevel element"
-        return self._last
-
-    def _flush(self):
-        if self._data:
-            text = "".join(self._data)
-            self._elem[-1].append(text)
-            self._data = []
-
-    ##
-    # Adds text to the current element.
-    #
-    # @param data A string.  This should be either an 8-bit string
-    #    containing ASCII text, or a Unicode string.
-
-    def data(self, data):
-        self._data.append(data)
-
-    ##
-    # Opens a new element.
-    #
-    # @param tag The element name.
-    # @param attrib A dictionary containing element attributes.
-    # @return The opened element.
-    # @defreturn Element
-
-    def start(self, tag, attrs):
-        self._flush()
-        self._last = elem = self._factory(tag, attrs)
-        if self._elem:
-            self._elem[-1].append(elem)
-        self._elem.append(elem)
-        return elem
-
-    ##
-    # Closes the current element.
-    #
-    # @param tag The element name.
-    # @return The closed element.
-    # @defreturn Element
-
-    def end(self, tag):
-        self._flush()
-        self._last = self._elem.pop()
-        assert self._last.tag == tag,\
-               "end tag mismatch (expected %s, got %s)" % (
-                   self._last.tag, tag)
-        return self._last
-
-##
-# Element structure builder for XML source data, based on the
-# <b>expat</b> parser.
-#
-# @keyparam target Target object.  If omitted, the builder uses an
-#     instance of the standard {@link #TreeBuilder} class.
-# @keyparam html Predefine HTML entities.  This flag is not supported
-#     by the current implementation.
-# @keyparam encoding Optional encoding.  If given, the value overrides
-#     the encoding specified in the XML file.
-# @see #ElementTree
-# @see #TreeBuilder
-
-class XMLParser(object):
-
-    def __init__(self, html=0, target=None, encoding=None):
-        try:
-            from xml.parsers import expat
-        except ImportError:
-            raise ImportError(
-                "No module named expat; use SimpleXMLTreeBuilder instead"
-                )
-        parser = expat.ParserCreate(encoding, "}")
-        if target is None:
-            target = TreeBuilder()
-        # underscored names are provided for compatibility only
-        self.parser = self._parser = parser
-        self.target = self._target = target
-        self._error = expat.error
-        self._names = {} # name memo cache
-        # callbacks
-        parser.DefaultHandlerExpand = self._default
-        parser.StartElementHandler = self._start
-        parser.EndElementHandler = self._end
-        parser.CharacterDataHandler = self._data
-        # let expat do the buffering, if supported
-        try:
-            self._parser.buffer_text = 1
-        except AttributeError:
-            pass
-        # use new-style attribute handling, if supported
-        try:
-            self._parser.ordered_attributes = 1
-            self._parser.specified_attributes = 1
-            parser.StartElementHandler = self._start_list
-        except AttributeError:
-            pass
-        self._doctype = None
-        self.entity = {}
-        try:
-            self.version = "Expat %d.%d.%d" % expat.version_info
-        except AttributeError:
-            pass # unknown
-
-    def _raiseerror(self, value):
-        err = ParseError(value)
-        err.code = value.code
-        err.position = value.lineno, value.offset
-        raise err
-
-    def _fixname(self, key):
-        # expand qname, and convert name string to ascii, if possible
-        if key in self._names:
-            return self._names[key].copy()
-        if '}' in key:
-            uri, name = key.split('}', 1)
-            name = QName(name, uri)
-        else:
-            name = QName(key)
-        self._names[key] = name
-        return name
-
-    def _start(self, tag, attrib_in):
-        fixname = self._fixname
-        tag = fixname(tag)
-        attrib = {}
-        for key, value in attrib_in.items():
-            attrib[fixname(key)] = value
-        return self.target.start(tag, attrib)
-
-    def _start_list(self, tag, attrib_in):
-        fixname = self._fixname
-        tag = fixname(tag)
-        attrib = {}
-        if attrib_in:
-            for i in range(0, len(attrib_in), 2):
-                attrib[fixname(attrib_in[i])] = attrib_in[i+1]
-        return self.target.start(tag, attrib)
-
-    def _data(self, text):
-        return self.target.data(text)
-
-    def _end(self, tag):
-        return self.target.end(self._fixname(tag))
-
-    def _default(self, text):
-        prefix = text[:1]
-        if prefix == "&":
-            # deal with undefined entities
-            try:
-                self.target.data(self.entity[text[1:-1]])
-            except KeyError:
-                from xml.parsers import expat
-                err = expat.error(
-                    "undefined entity %s: line %d, column %d" %
-                    (text, self._parser.ErrorLineNumber,
-                    self._parser.ErrorColumnNumber)
-                    )
-                err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
-                err.lineno = self._parser.ErrorLineNumber
-                err.offset = self._parser.ErrorColumnNumber
-                raise err
-        elif prefix == "<" and text[:9] == "<!DOCTYPE":
-            self._doctype = [] # inside a doctype declaration
-        elif self._doctype is not None:
-            # parse doctype contents
-            if prefix == ">":
-                self._doctype = None
-                return
-            text = text.strip()
-            if not text:
-                return
-            self._doctype.append(text)
-            n = len(self._doctype)
-            if n > 2:
-                type = self._doctype[1]
-                if type == "PUBLIC" and n == 4:
-                    name, type, pubid, system = self._doctype
-                elif type == "SYSTEM" and n == 3:
-                    name, type, system = self._doctype
-                    pubid = None
-                else:
-                    return
-                if pubid:
-                    pubid = pubid[1:-1]
-                if hasattr(self.target, "doctype"):
-                    self.target.doctype(name, pubid, system[1:-1])
-                self._doctype = None
-
-    ##
-    # Feeds data to the parser.
-    #
-    # @param data Encoded data.
-
-    def feed(self, data):
-        try:
-            self._parser.Parse(data, 0)
-        except self._error, v:
-            self._raiseerror(v)
-
-    ##
-    # Finishes feeding data to the parser.
-    #
-    # @return An element structure.
-    # @defreturn Element
-
-    def close(self):
-        try:
-            self._parser.Parse("", 1) # end of data
-        except self._error, v:
-            self._raiseerror(v)
-        tree = self.target.close()
-        del self.target, self._parser # get rid of circular references
-        return tree
-
+from emeraldtree.tree import *
--- a/emeraldtree/tests/test_ElementTree.py	Mon Jul 20 11:07:06 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,273 +0,0 @@
-import py.test
-from emeraldtree.ElementTree import *
-
-def serialize(elem, **options):
-    from cStringIO import StringIO
-    file = StringIO()
-    tree = ElementTree(elem)
-    tree.write(file, **options)
-    return file.getvalue()
-
-def test_Element():
-    elem = Element('a')
-
-    assert isinstance(elem, Node)
-    assert elem.tag == 'a'
-
-def test_Element__len__():
-    elem = Element('a', children=['1', '2', '3', '4', '5'])
-
-    assert len(elem) == 5
-
-def test_Element__nonzero__():
-    elem = Element('a')
-
-    assert elem
-    assert len(elem) == 0
-
-def test_Element___getitem__():
-    elem = Element('a', children = [Element('b'), Element('c')])
-
-    assert elem[0].tag == 'b'
-    assert elem[1].tag == 'c'
-    assert len(elem[:1]) == 1
-    assert len(elem[:2]) == 2
-    assert len(elem[:3]) == 2
-    assert len(elem[1:3]) == 1
-    assert len(elem[2:3]) == 0
-    assert elem[:2][0].tag == 'b'
-    assert elem[:2][1].tag == 'c'
-
-def test_Element___setitem__():
-    elem = Element('a', children = [Element('b1'), Element('b2')])
-
-    elem[0] = Element('c')
-    assert elem[0].tag == 'c'
-    assert elem[1].tag == 'b2'
-
-    elem[1] = Element('d')
-    assert elem[0].tag == 'c'
-    assert elem[1].tag == 'd'
-
-    elem[0:0] = [Element('e')]
-    assert elem[0].tag == 'e'
-    assert elem[1].tag == 'c'
-    assert elem[2].tag == 'd'
-
-def test_Element___delitem__():
-    elem = Element('a', children = [Element('b1'), Element('b2')])
-
-    del elem[0]
-    assert len(elem) == 1
-    assert elem[0].tag == 'b2'
-
-def test_Element_append():
-    elem = Element('a')
-
-    elem.append(Element('b'))
-    assert len(elem) == 1
-    assert elem[0].tag == 'b'
-
-    elem.append(Element('c'))
-    assert len(elem) == 2
-    assert elem[1].tag == 'c'
-
-    elem.append('d')
-    assert len(elem) == 3
-    assert elem[2] == 'd'
-
-def test_Element_extend():
-    pass
-
-def test_Element_insert():
-    pass
-
-def test_Element_remove():
-    pass
-
-def test_Element_find():
-    child_1 = Element('b1')
-    child_2 = Element('b2')
-    elem = Element('a', children=[child_1, child_2])
-
-    result = elem.find('b1')
-    assert result is child_1
-
-    result = elem.find('b2')
-    assert result is child_2
-
-    child_1 = Element(QName('b1', 'url1'))
-    child_2 = Element(QName('{url2}b2'))
-    elem = Element('a', children=[child_1, child_2])
-
-    result = elem.find('{url1}b1')
-    assert result is child_1
-
-def test_Element_findtext():
-    pass
-
-def test_Element_findall():
-    child_1 = Element('b1')
-    child_2 = Element('b2')
-    child_3 = u"text"
-    elem = Element('a', children=[child_1, child_2, child_3])
-
-    result = list(elem.findall('b1'))
-    assert len(result) == 1
-    assert result[0] is child_1
-
-    result = list(elem.findall('b2'))
-    assert len(result) == 1
-    assert result[0] is child_2
-
-    result = list(elem.findall('*'))
-    assert len(result) == 3
-    assert result[0] is child_1
-    assert result[1] is child_2
-    assert result[2] is child_3
-
-    child_1 = Element(QName('b1', 'url1'))
-    child_2 = Element(QName('{url2}b2'))
-    elem = Element('a', children=[child_1, child_2])
-
-    result = list(elem.findall('{url1}b1'))
-    assert len(result) == 1
-    assert result[0] is child_1
-
-def test_Element_clear():
-    pass
-
-def test_Element_get():
-    pass
-
-def test_Element_set():
-    pass
-
-def test_Element_keys():
-    pass
-
-def test_Element_items():
-    pass
-
-def test_Element_iter():
-    elem = Element('a')
-    l = list(elem.iter())
-    assert len(l) == 1
-
-    elem.append('b')
-    l = list(elem.iter())
-    assert len(l) == 2
-
-    elem.append(Element('c'))
-    l = list(elem.iter())
-    assert len(l) == 3
-
-    elem.append('d')
-    l = list(elem.iter())
-    assert len(l) == 4
-
-def test_Element_itertext():
-    elem = Element('a')
-    l = list(elem.itertext())
-    assert len(l) == 0
-
-    elem.append('b')
-    l = list(elem.itertext())
-    assert len(l) == 1
-
-def test_Comment():
-    elem = Comment('a')
-    assert serialize(elem) == '<!--a-->'
-    assert isinstance(elem, Node)
-
-def test_ProcessingInstruction():
-    elem = ProcessingInstruction('a')
-    assert serialize(elem) == '<?a?>'
-    assert isinstance(elem, ProcessingInstruction)
-
-    elem = ProcessingInstruction('a', 'b')
-    assert serialize(elem) == '<?a b?>'
-
-def test_QName___init__():
-    qname = QName('a')
-    assert qname.uri is None
-    assert qname.name == 'a'
-    assert isinstance(qname.name, unicode)
-    assert str(qname) == 'a'
-    assert qname.text == 'a'
-
-    qname = QName('{b}a')
-    assert qname.uri == 'b'
-    assert isinstance(qname.uri, unicode)
-    assert qname.name == 'a'
-    assert str(qname) == '{b}a'
-    assert qname.text == '{b}a'
-
-    qname = QName('a', 'b')
-    assert qname.uri == 'b'
-    assert qname.name == 'a'
-    assert str(qname) == '{b}a'
-    assert qname.text == '{b}a'
-
-    py.test.raises(ValueError, QName, '{ba')
-    py.test.raises(ValueError, QName, '{b}a', 'c')
-
-def test_QName___cmp__():
-    qname1 = QName('a')
-    qname2 = QName('a')
-
-    assert qname1 == qname2
-    assert qname1 == 'a'
-    assert 'a' == qname1
-
-    qname1 = QName('a', 'b')
-    qname2 = QName('{b}a')
-
-    assert qname1 == qname2
-    assert qname1 == '{b}a'
-    assert '{b}a' == qname1
-
-def test_XMLParser_simple1():
-    elem = XML('<a />')
-    assert elem.tag == 'a'
-    assert len(elem) == 0
-
-def test_XMLParser_simple2():
-    elem = XML('<a><b /></a>')
-    assert elem.tag == 'a'
-    assert len(elem) == 1
-    assert elem[0].tag == 'b'
-    assert len(elem[0]) == 0
-
-def test_XMLParser_text1():
-    elem = XML('<a>b</a>')
-    assert elem.tag == 'a'
-    assert isinstance(elem, Element)
-    assert len(elem) == 1
-    assert elem[0] == 'b'
-    assert isinstance(elem[0], unicode)
-
-def test_XMLParser_text2():
-    elem = XML('<a>b<c>d</c>d</a>')
-    assert elem.tag == 'a'
-    assert len(elem) == 3
-    assert elem[0] == 'b'
-    assert elem[1].tag == 'c'
-    assert elem[2] == 'd'
-
-def test_XMLParser_namespace():
-    elem = XML('<b xmlns="c" d="e"/>')
-    assert isinstance(elem.tag, QName)
-    assert elem.tag == QName('b', 'c')
-    assert elem.attrib == {QName('d', None): 'e'}
-    assert serialize(elem) == '<ns0:b d="e" xmlns:ns0="c" />'
-    assert serialize(elem, default_namespace='c') == '<b d="e" xmlns="c" />'
-
-    elem = XML('<a:b xmlns:a="c" d="e" a:f="g"/>')
-    assert isinstance(elem.tag, QName)
-    assert elem.tag == QName('b', 'c')
-    assert elem.attrib == {'d': 'e', QName('f', 'c'): 'g'}
-    assert serialize(elem) == '<ns0:b d="e" ns0:f="g" xmlns:ns0="c" />'
-    assert serialize(elem, default_namespace='c') == '<b d="e" f="g" xmlns="c" />'
-
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/emeraldtree/tests/test_tree.py	Mon Jul 20 11:08:47 2009 +0200
@@ -0,0 +1,273 @@
+import py.test
+from emeraldtree.tree import *
+
+def serialize(elem, **options):
+    from cStringIO import StringIO
+    file = StringIO()
+    tree = ElementTree(elem)
+    tree.write(file, **options)
+    return file.getvalue()
+
+def test_Element():
+    elem = Element('a')
+
+    assert isinstance(elem, Node)
+    assert elem.tag == 'a'
+
+def test_Element__len__():
+    elem = Element('a', children=['1', '2', '3', '4', '5'])
+
+    assert len(elem) == 5
+
+def test_Element__nonzero__():
+    elem = Element('a')
+
+    assert elem
+    assert len(elem) == 0
+
+def test_Element___getitem__():
+    elem = Element('a', children = [Element('b'), Element('c')])
+
+    assert elem[0].tag == 'b'
+    assert elem[1].tag == 'c'
+    assert len(elem[:1]) == 1
+    assert len(elem[:2]) == 2
+    assert len(elem[:3]) == 2
+    assert len(elem[1:3]) == 1
+    assert len(elem[2:3]) == 0
+    assert elem[:2][0].tag == 'b'
+    assert elem[:2][1].tag == 'c'
+
+def test_Element___setitem__():
+    elem = Element('a', children = [Element('b1'), Element('b2')])
+
+    elem[0] = Element('c')
+    assert elem[0].tag == 'c'
+    assert elem[1].tag == 'b2'
+
+    elem[1] = Element('d')
+    assert elem[0].tag == 'c'
+    assert elem[1].tag == 'd'
+
+    elem[0:0] = [Element('e')]
+    assert elem[0].tag == 'e'
+    assert elem[1].tag == 'c'
+    assert elem[2].tag == 'd'
+
+def test_Element___delitem__():
+    elem = Element('a', children = [Element('b1'), Element('b2')])
+
+    del elem[0]
+    assert len(elem) == 1
+    assert elem[0].tag == 'b2'
+
+def test_Element_append():
+    elem = Element('a')
+
+    elem.append(Element('b'))
+    assert len(elem) == 1
+    assert elem[0].tag == 'b'
+
+    elem.append(Element('c'))
+    assert len(elem) == 2
+    assert elem[1].tag == 'c'
+
+    elem.append('d')
+    assert len(elem) == 3
+    assert elem[2] == 'd'
+
+def test_Element_extend():
+    pass
+
+def test_Element_insert():
+    pass
+
+def test_Element_remove():
+    pass
+
+def test_Element_find():
+    child_1 = Element('b1')
+    child_2 = Element('b2')
+    elem = Element('a', children=[child_1, child_2])
+
+    result = elem.find('b1')
+    assert result is child_1
+
+    result = elem.find('b2')
+    assert result is child_2
+
+    child_1 = Element(QName('b1', 'url1'))
+    child_2 = Element(QName('{url2}b2'))
+    elem = Element('a', children=[child_1, child_2])
+
+    result = elem.find('{url1}b1')
+    assert result is child_1
+
+def test_Element_findtext():
+    pass
+
+def test_Element_findall():
+    child_1 = Element('b1')
+    child_2 = Element('b2')
+    child_3 = u"text"
+    elem = Element('a', children=[child_1, child_2, child_3])
+
+    result = list(elem.findall('b1'))
+    assert len(result) == 1
+    assert result[0] is child_1
+
+    result = list(elem.findall('b2'))
+    assert len(result) == 1
+    assert result[0] is child_2
+
+    result = list(elem.findall('*'))
+    assert len(result) == 3
+    assert result[0] is child_1
+    assert result[1] is child_2
+    assert result[2] is child_3
+
+    child_1 = Element(QName('b1', 'url1'))
+    child_2 = Element(QName('{url2}b2'))
+    elem = Element('a', children=[child_1, child_2])
+
+    result = list(elem.findall('{url1}b1'))
+    assert len(result) == 1
+    assert result[0] is child_1
+
+def test_Element_clear():
+    pass
+
+def test_Element_get():
+    pass
+
+def test_Element_set():
+    pass
+
+def test_Element_keys():
+    pass
+
+def test_Element_items():
+    pass
+
+def test_Element_iter():
+    elem = Element('a')
+    l = list(elem.iter())
+    assert len(l) == 1
+
+    elem.append('b')
+    l = list(elem.iter())
+    assert len(l) == 2
+
+    elem.append(Element('c'))
+    l = list(elem.iter())
+    assert len(l) == 3
+
+    elem.append('d')
+    l = list(elem.iter())
+    assert len(l) == 4
+
+def test_Element_itertext():
+    elem = Element('a')
+    l = list(elem.itertext())
+    assert len(l) == 0
+
+    elem.append('b')
+    l = list(elem.itertext())
+    assert len(l) == 1
+
+def test_Comment():
+    elem = Comment('a')
+    assert serialize(elem) == '<!--a-->'
+    assert isinstance(elem, Node)
+
+def test_ProcessingInstruction():
+    elem = ProcessingInstruction('a')
+    assert serialize(elem) == '<?a?>'
+    assert isinstance(elem, ProcessingInstruction)
+
+    elem = ProcessingInstruction('a', 'b')
+    assert serialize(elem) == '<?a b?>'
+
+def test_QName___init__():
+    qname = QName('a')
+    assert qname.uri is None
+    assert qname.name == 'a'
+    assert isinstance(qname.name, unicode)
+    assert str(qname) == 'a'
+    assert qname.text == 'a'
+
+    qname = QName('{b}a')
+    assert qname.uri == 'b'
+    assert isinstance(qname.uri, unicode)
+    assert qname.name == 'a'
+    assert str(qname) == '{b}a'
+    assert qname.text == '{b}a'
+
+    qname = QName('a', 'b')
+    assert qname.uri == 'b'
+    assert qname.name == 'a'
+    assert str(qname) == '{b}a'
+    assert qname.text == '{b}a'
+
+    py.test.raises(ValueError, QName, '{ba')
+    py.test.raises(ValueError, QName, '{b}a', 'c')
+
+def test_QName___cmp__():
+    qname1 = QName('a')
+    qname2 = QName('a')
+
+    assert qname1 == qname2
+    assert qname1 == 'a'
+    assert 'a' == qname1
+
+    qname1 = QName('a', 'b')
+    qname2 = QName('{b}a')
+
+    assert qname1 == qname2
+    assert qname1 == '{b}a'
+    assert '{b}a' == qname1
+
+def test_XMLParser_simple1():
+    elem = XML('<a />')
+    assert elem.tag == 'a'
+    assert len(elem) == 0
+
+def test_XMLParser_simple2():
+    elem = XML('<a><b /></a>')
+    assert elem.tag == 'a'
+    assert len(elem) == 1
+    assert elem[0].tag == 'b'
+    assert len(elem[0]) == 0
+
+def test_XMLParser_text1():
+    elem = XML('<a>b</a>')
+    assert elem.tag == 'a'
+    assert isinstance(elem, Element)
+    assert len(elem) == 1
+    assert elem[0] == 'b'
+    assert isinstance(elem[0], unicode)
+
+def test_XMLParser_text2():
+    elem = XML('<a>b<c>d</c>d</a>')
+    assert elem.tag == 'a'
+    assert len(elem) == 3
+    assert elem[0] == 'b'
+    assert elem[1].tag == 'c'
+    assert elem[2] == 'd'
+
+def test_XMLParser_namespace():
+    elem = XML('<b xmlns="c" d="e"/>')
+    assert isinstance(elem.tag, QName)
+    assert elem.tag == QName('b', 'c')
+    assert elem.attrib == {QName('d', None): 'e'}
+    assert serialize(elem) == '<ns0:b d="e" xmlns:ns0="c" />'
+    assert serialize(elem, default_namespace='c') == '<b d="e" xmlns="c" />'
+
+    elem = XML('<a:b xmlns:a="c" d="e" a:f="g"/>')
+    assert isinstance(elem.tag, QName)
+    assert elem.tag == QName('b', 'c')
+    assert elem.attrib == {'d': 'e', QName('f', 'c'): 'g'}
+    assert serialize(elem) == '<ns0:b d="e" ns0:f="g" xmlns:ns0="c" />'
+    assert serialize(elem, default_namespace='c') == '<b d="e" f="g" xmlns="c" />'
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/emeraldtree/tree.py	Mon Jul 20 11:08:47 2009 +0200
@@ -0,0 +1,1436 @@
+#
+# ElementTree
+# $Id: ElementTree.py 3276 2007-09-12 06:52:30Z fredrik $
+#
+# light-weight XML support for Python 2.2 and later.
+#
+# history:
+# 2001-10-20 fl   created (from various sources)
+# 2001-11-01 fl   return root from parse method
+# 2002-02-16 fl   sort attributes in lexical order
+# 2002-04-06 fl   TreeBuilder refactoring, added PythonDoc markup
+# 2002-05-01 fl   finished TreeBuilder refactoring
+# 2002-07-14 fl   added basic namespace support to ElementTree.write
+# 2002-07-25 fl   added QName attribute support
+# 2002-10-20 fl   fixed encoding in write
+# 2002-11-24 fl   changed default encoding to ascii; fixed attribute encoding
+# 2002-11-27 fl   accept file objects or file names for parse/write
+# 2002-12-04 fl   moved XMLTreeBuilder back to this module
+# 2003-01-11 fl   fixed entity encoding glitch for us-ascii
+# 2003-02-13 fl   added XML literal factory
+# 2003-02-21 fl   added ProcessingInstruction/PI factory
+# 2003-05-11 fl   added tostring/fromstring helpers
+# 2003-05-26 fl   added ElementPath support
+# 2003-07-05 fl   added makeelement factory method
+# 2003-07-28 fl   added more well-known namespace prefixes
+# 2003-08-15 fl   fixed typo in ElementTree.findtext (Thomas Dartsch)
+# 2003-09-04 fl   fall back on emulator if ElementPath is not installed
+# 2003-10-31 fl   markup updates
+# 2003-11-15 fl   fixed nested namespace bug
+# 2004-03-28 fl   added XMLID helper
+# 2004-06-02 fl   added default support to findtext
+# 2004-06-08 fl   fixed encoding of non-ascii element/attribute names
+# 2004-08-23 fl   take advantage of post-2.1 expat features
+# 2004-09-03 fl   made Element class visible; removed factory
+# 2005-02-01 fl   added iterparse implementation
+# 2005-03-02 fl   fixed iterparse support for pre-2.2 versions
+# 2005-11-12 fl   added tostringlist/fromstringlist helpers
+# 2006-07-05 fl   merged in selected changes from the 1.3 sandbox
+# 2006-07-05 fl   removed support for 2.1 and earlier
+# 2007-06-21 fl   added deprecation/future warnings
+# 2007-08-25 fl   added doctype hook, added parser version attribute etc
+# 2007-08-26 fl   added new serializer code (better namespace handling, etc)
+# 2007-08-27 fl   warn for broken /tag searches on tree level
+# 2007-09-02 fl   added html/text methods to serializer (experimental)
+# 2007-09-05 fl   added method argument to tostring/tostringlist
+# 2007-09-06 fl   improved error handling
+#
+# Copyright (c) 1999-2007 by Fredrik Lundh.  All rights reserved.
+#
+# fredrik@pythonware.com
+# http://www.pythonware.com
+#
+# --------------------------------------------------------------------
+# The ElementTree toolkit is
+#
+# Copyright (c) 1999-2007 by Fredrik Lundh
+#               2008 Bastian Blank <bblank@thinkmo.de>
+#
+# By obtaining, using, and/or copying this software and/or its
+# associated documentation, you agree that you have read, understood,
+# and will comply with the following terms and conditions:
+#
+# Permission to use, copy, modify, and distribute this software and
+# its associated documentation for any purpose and without fee is
+# hereby granted, provided that the above copyright notice appears in
+# all copies, and that both that copyright notice and this permission
+# notice appear in supporting documentation, and that the name of
+# Secret Labs AB or the author not be used in advertising or publicity
+# pertaining to distribution of the software without specific, written
+# prior permission.
+#
+# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
+# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
+# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
+# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
+# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+# OF THIS SOFTWARE.
+# --------------------------------------------------------------------
+
+from __future__ import generators
+
+__all__ = [
+    # public symbols
+    "Comment",
+    "dump",
+    "Element", "ElementTree",
+    "fromstring", "fromstringlist",
+    "iterparse",
+    "Node",
+    "parse", "ParseError",
+    "PI", "ProcessingInstruction",
+    "QName",
+    "SubElement",
+    "tostring", "tostringlist",
+    "TreeBuilder",
+    "XML",
+    "XMLParser",
+    ]
+
+##
+# The <b>Element</b> type is a flexible container object, designed to
+# store hierarchical data structures in memory. The type can be
+# described as a cross between a list and a dictionary.
+# <p>
+# Each element has a number of properties associated with it:
+# <ul>
+# <li>a <i>tag</i>. This is a string identifying what kind of data
+# this element represents (the element type, in other words).</li>
+# <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
+# <li>a <i>text</i> string.</li>
+# <li>an optional <i>tail</i> string.</li>
+# <li>a number of <i>child elements</i>, stored in a Python sequence</li>
+# </ul>
+#
+# To create an element instance, use the {@link #Element} constructor
+# or the {@link #SubElement} factory function.
+# <p>
+# The {@link #ElementTree} class can be used to wrap an element
+# structure, and convert it from and to XML.
+##
+
+import ElementPath
+
+class ParseError(SyntaxError):
+    pass
+
+# --------------------------------------------------------------------
+
+class Node(object):
+    """
+    Node class.
+    """
+
+##
+# Element class.  This class defines the Element interface, and
+# provides a reference implementation of this interface.
+# <p>
+# The element name, attribute names, and attribute values can be
+# either 8-bit ASCII strings or Unicode strings.
+#
+# @param tag The element name.
+# @param attrib An optional dictionary, containing element attributes.
+# @param **extra Additional attributes, given as keyword arguments.
+# @see Element
+# @see SubElement
+# @see Comment
+# @see ProcessingInstruction
+
+class Element(Node):
+    # <tag attrib>text<child/>...</tag>tail
+
+    ##
+    # (Attribute) Element tag.
+
+    tag = None
+
+    ##
+    # (Attribute) Element attribute dictionary.  Where possible, use
+    # {@link #Element.get},
+    # {@link #Element.set},
+    # {@link #Element.keys}, and
+    # {@link #Element.items} to access
+    # element attributes.
+
+    attrib = None
+
+    ##
+    # (Attribute) Text before first subelement.  This is either a
+    # string or the value None, if there was no text.
+
+    @property
+    def text(self):
+        if len(self) and isinstance(self[0], basestring):
+            return self[0]
+
+    ##
+    # (Attribute) Text after this element's end tag, but before the
+    # next sibling element's start tag.  This is either a string or
+    # the value None, if there was no text.
+
+    @property
+    def tail(self):
+        raise RuntimeError('The tail argument is not supported')
+
+    def __init__(self, tag, attrib=None, children=(), **extra):
+        if attrib:
+            if isinstance(attrib, dict):
+                attrib = attrib.copy()
+            else:
+                raise TypeError('attrib')
+        else:
+            attrib = {}
+        attrib.update(extra)
+        self.tag = tag
+        self.attrib = attrib
+        self._children = [self._check_node(i) for i in children]
+
+    def __repr__(self):
+        return "<Element %s at %x>" % (repr(self.tag), id(self))
+
+    ##
+    # Returns the number of subelements.
+    #
+    # @return The number of subelements.
+
+    def __len__(self):
+        return len(self._children)
+
+    def __nonzero__(self):
+        return True
+
+    ##
+    # Returns the given subelement.
+    #
+    # @param index What subelement to return.
+    # @return The given subelement.
+    # @exception IndexError If the given element does not exist.
+
+    def __getitem__(self, index):
+        return self._children.__getitem__(index)
+
+    ##
+    # Replaces the given subelement.
+    #
+    # @param index What subelement to replace.
+    # @param element The new element value.
+    # @exception IndexError If the given element does not exist.
+    # @exception AssertionError If element is not a valid object.
+
+    def __setitem__(self, index, element):
+        if isinstance(index, slice):
+            element = [self._check_node(i) for i in element]
+        else:
+            element = self._check_node(element)
+        self._children.__setitem__(index, element)
+
+    ##
+    # Deletes the given subelement.
+    #
+    # @param index What subelement to delete.
+    # @exception IndexError If the given element does not exist.
+
+    def __delitem__(self, index):
+        self._children.__delitem__(index)
+
+    @staticmethod
+    def _check_node(node):
+        if isinstance(node, (Node, unicode)):
+            return node
+        if isinstance(node, str):
+            return unicode(node)
+        raise TypeError
+
+    ##
+    # Adds a subelement to the end of this element.
+    #
+    # @param element The element to add.
+    # @exception AssertionError If a sequence member is not a valid object.
+
+    def append(self, element):
+        element = self._check_node(element)
+        self._children.append(element)
+
+    ##
+    # Appends subelements from a sequence.
+    #
+    # @param elements A sequence object with zero or more elements.
+    # @exception AssertionError If a subelement is not a valid object.
+    # @since 1.3
+
+    def extend(self, elements):
+        elements = [self._check_node(i) for i in elements]
+        self._children.extend(elements)
+
+    ##
+    # Inserts a subelement at the given position in this element.
+    #
+    # @param index Where to insert the new subelement.
+    # @exception AssertionError If the element is not a valid object.
+
+    def insert(self, index, element):
+        element = self._check_node(element)
+        self._children.insert(index, element)
+
+    ##
+    # Removes a matching subelement.  Unlike the <b>find</b> methods,
+    # this method compares elements based on identity, not on tag
+    # value or contents.
+    #
+    # @param element What element to remove.
+    # @exception ValueError If a matching element could not be found.
+    # @exception AssertionError If the element is not a valid object.
+
+    def remove(self, element):
+        self._children.remove(element)
+
+    ##
+    # Finds the first matching subelement, by tag name or path.
+    #
+    # @param path What element to look for.
+    # @return The first matching element, or None if no element was found.
+    # @defreturn Element or None
+
+    def find(self, path):
+        return ElementPath.find(self, path)
+
+    ##
+    # Finds text for the first matching subelement, by tag name or path.
+    #
+    # @param path What element to look for.
+    # @param default What to return if the element was not found.
+    # @return The text content of the first matching element, or the
+    #     default value no element was found.  Note that if the element
+    #     has is found, but has no text content, this method returns an
+    #     empty string.
+    # @defreturn string
+
+    def findtext(self, path, default=None):
+        return ElementPath.findtext(self, path, default)
+
+    ##
+    # Finds all matching subelements, by tag name or path.
+    #
+    # @param path What element to look for.
+    # @return A list or iterator containing all matching elements,
+    #    in document order.
+    # @defreturn list of Element instances
+
+    def findall(self, path):
+        return ElementPath.findall(self, path)
+
+    ##
+    # Resets an element.  This function removes all subelements, clears
+    # all attributes, and sets the text and tail attributes to None.
+
+    def clear(self):
+        self.attrib.clear()
+        self._children = []
+
+    ##
+    # Gets an element attribute.
+    #
+    # @param key What attribute to look for.
+    # @param default What to return if the attribute was not found.
+    # @return The attribute value, or the default value, if the
+    #     attribute was not found.
+
+    def get(self, key, default=None):
+        return self.attrib.get(key, default)
+
+    ##
+    # Sets an element attribute.
+    #
+    # @param key What attribute to set.
+    # @param value The attribute value.
+
+    def set(self, key, value):
+        self.attrib[key] = value
+
+    ##
+    # Gets a list of attribute names.  The names are returned in an
+    # arbitrary order (just like for an ordinary Python dictionary).
+    #
+    # @return A list of element attribute names.
+    # @defreturn list of strings
+
+    def keys(self):
+        return self.attrib.keys()
+
+    ##
+    # Gets element attributes, as a sequence.  The attributes are
+    # returned in an arbitrary order.
+    #
+    # @return A list of (name, value) tuples for all attributes.
+    # @defreturn list of (string, string) tuples
+
+    def items(self):
+        return self.attrib.items()
+
+    def __iter__(self):
+        """
+        Creates a element iterator.  The iterator loops over all children.
+        """
+        return self._children.__iter__()
+
+    ##
+    # Creates a tree iterator.  The iterator loops over this element
+    # and all subelements, in document order, and returns all elements
+    # with a matching tag.
+    # <p>
+    # If the tree structure is modified during iteration, new or removed
+    # elements may or may not be included.  To get a stable set, use the
+    # list() function on the iterator, and loop over the resulting list.
+    #
+    # @param tag What tags to look for (default is to return all elements).
+    # @return An iterator containing all the matching elements.
+    # @defreturn iterator
+
+    def iter(self, tag=None):
+        if tag == "*":
+            tag = None
+        if tag is None or self.tag == tag:
+            yield self
+        for e in self._children:
+            if isinstance(e, Element):
+                for e in e.iter(tag):
+                    yield e
+            else:
+                yield e
+
+    ##
+    # Creates a text iterator.  The iterator loops over this element
+    # and all subelements, in document order, and returns all inner
+    # text.
+    #
+    # @return An iterator containing all inner text.
+    # @defreturn iterator
+
+    def itertext(self):
+        for e in self:
+            if isinstance(e, Element):
+                for s in e.itertext():
+                    yield s
+            elif isinstance(e, basestring):
+                yield e
+
+##
+# Subelement factory.  This function creates an element instance, and
+# appends it to an existing element.
+# <p>
+# The element name, attribute names, and attribute values can be
+# either 8-bit ASCII strings or Unicode strings.
+#
+# @param parent The parent element.
+# @param tag The subelement name.
+# @param attrib An optional dictionary, containing element attributes.
+# @param **extra Additional attributes, given as keyword arguments.
+# @return An element instance.
+# @defreturn Element
+
+def SubElement(parent, tag, attrib=None, **extra):
+    attrib = attrib and attrib.copy() or {}
+    attrib.update(extra)
+    element = parent.makeelement(tag, attrib)
+    parent.append(element)
+    return element
+
+##
+# Comment element factory.  This factory function creates a special
+# element that will be serialized as an XML comment by the standard
+# serializer.
+# <p>
+# The comment string can be either an 8-bit ASCII string or a Unicode
+# string.
+#
+# @param text A string containing the comment string.
+# @return An element instance, representing a comment.
+# @defreturn Element
+
+class Comment(Node):
+    def __init__(self, text = None):
+        self.text = text
+
+##
+# PI element factory.  This factory function creates a special element
+# that will be serialized as an XML processing instruction by the standard
+# serializer.
+#
+# @param target A string containing the PI target.
+# @param text A string containing the PI contents, if any.
+# @return An element instance, representing a PI.
+# @defreturn Element
+
+class ProcessingInstruction(Node):
+    def __init__(self, target, text = None):
+        self.target, self.text = target, text
+
+PI = ProcessingInstruction
+
+##
+# QName wrapper.  This can be used to wrap a QName attribute value, in
+# order to get proper namespace handling on output.
+#
+# @return An opaque object, representing the QName.
+
+class QName(unicode):
+    __slots__ = 'name', 'uri'
+
+    def __new__(cls, name, uri=None):
+        text = name = unicode(name)
+
+        if name[0] == '{':
+            if uri is not None:
+                raise ValueError
+            i = name.find('}')
+            if i == -1:
+                raise ValueError
+            uri = name[1:i]
+            name = name[i + 1:]
+
+        if uri is not None:
+            uri = unicode(uri)
+            text = '{' + uri + '}' + name
+
+        ret = unicode.__new__(cls, text)
+        unicode.__setattr__(ret, 'name', name)
+        unicode.__setattr__(ret, 'uri', uri)
+
+        return ret
+
+    def __getnewargs__(self):
+        return self.name, self.uri
+
+    def __getstate__(self):
+        pass
+
+    def __repr__(self):
+        return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.uri)
+
+    def __setattr__(self, key, value):
+        raise AttributeError('read-only')
+
+    def copy(self):
+        return self.__class__(self.name, self.uri)
+
+    @property
+    def text(self):
+        return self
+
+# --------------------------------------------------------------------
+
+##
+# ElementTree wrapper class.  This class represents an entire element
+# hierarchy, and adds some extra support for serialization to and from
+# standard XML.
+#
+# @param element Optional root element.
+# @keyparam file Optional file handle or file name.  If given, the
+#     tree is initialized with the contents of this XML file.
+
+class ElementTree(object):
+
+    def __init__(self, element=None, file=None):
+        assert element is None or isinstance(element, Node)
+        self._root = element # first node
+        if file:
+            self.parse(file)
+
+    ##
+    # Gets the root element for this tree.
+    #
+    # @return An element instance.
+    # @defreturn Element
+
+    def getroot(self):
+        return self._root
+
+    ##
+    # Loads an external XML document into this element tree.
+    #
+    # @param source A file name or file object.
+    # @keyparam parser An optional parser instance.  If not given, the
+    #     standard {@link XMLParser} parser is used.
+    # @return The document root element.
+    # @defreturn Element
+
+    def parse(self, source, parser=None):
+        if not hasattr(source, "read"):
+            source = open(source, "rb")
+        if not parser:
+            parser = XMLParser(target=TreeBuilder())
+        while 1:
+            data = source.read(32768)
+            if not data:
+                break
+            parser.feed(data)
+        self._root = parser.close()
+        return self._root
+
+    ##
+    # Creates a tree iterator for the root element.  The iterator loops
+    # over all elements in this tree, in document order.
+    #
+    # @param tag What tags to look for (default is to return all elements)
+    # @return An iterator.
+    # @defreturn iterator
+
+    def iter(self, tag=None):
+        assert self._root is not None
+        return self._root.iter(tag)
+
+    getiterator = iter
+
+    ##
+    # Finds the first toplevel element with given tag.
+    # Same as getroot().find(path).
+    #
+    # @param path What element to look for.
+    # @return The first matching element, or None if no element was found.
+    # @defreturn Element or None
+
+    def find(self, path):
+        assert self._root is not None
+        if path[:1] == "/":
+            path = "." + path
+            import warnings
+            warnings.warn(
+                "This search is broken in 1.3 and earlier; if you rely "
+                "on the current behaviour, change it to %r" % path,
+                FutureWarning
+                )
+        return self._root.find(path)
+
+    ##
+    # Finds the element text for the first toplevel element with given
+    # tag.  Same as getroot().findtext(path).
+    #
+    # @param path What toplevel element to look for.
+    # @param default What to return if the element was not found.
+    # @return The text content of the first matching element, or the
+    #     default value no element was found.  Note that if the element
+    #     has is found, but has no text content, this method returns an
+    #     empty string.
+    # @defreturn string
+
+    def findtext(self, path, default=None):
+        assert self._root is not None
+        if path[:1] == "/":
+            path = "." + path
+            import warnings
+            warnings.warn(
+                "This search is broken in 1.3 and earlier; if you rely "
+                "on the current behaviour, change it to %r" % path,
+                FutureWarning
+                )
+        return self._root.findtext(path, default)
+
+    ##
+    # Finds all toplevel elements with the given tag.
+    # Same as getroot().findall(path).
+    #
+    # @param path What element to look for.
+    # @return A list or iterator containing all matching elements,
+    #    in document order.
+    # @defreturn list of Element instances
+
+    def findall(self, path):
+        assert self._root is not None
+        if path[:1] == "/":
+            path = "." + path
+            import warnings
+            warnings.warn(
+                "This search is broken in 1.3 and earlier; if you rely "
+                "on the current behaviour, change it to %r" % path,
+                FutureWarning
+                )
+        return self._root.findall(path)
+
+    ##
+    # Writes the element tree to a file, as XML.
+    #
+    # @param file A file name, or a file object opened for writing.
+    # @keyparam encoding Optional output encoding (default is US-ASCII).
+    # @keyparam method Optional output method ("xml" or "html"; default
+    #     is "xml".
+    # @keyparam xml_declaration Controls if an XML declaration should
+    #     be added to the file.  Use False for never, True for always,
+    #     None for only if not US-ASCII or UTF-8.  None is default.
+
+    def write(self, file,
+              # keyword arguments
+              encoding="us-ascii",
+              xml_declaration=None,
+              default_namespace=None,
+              method=None,
+              namespaces=None):
+        assert self._root is not None
+        if not hasattr(file, "write"):
+            file = open(file, "wb")
+        write = file.write
+        if not method:
+            method = "xml"
+        elif method == 'html':
+            default_namespace = "http://www.w3.org/1999/xhtml"
+        if not encoding:
+            encoding = "us-ascii"
+        elif xml_declaration or (xml_declaration is None and
+                                 encoding not in ("utf-8", "us-ascii")):
+            write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
+        if method == "text":
+            _serialize_text(write, self._root, encoding)
+        else:
+            qnames, namespaces = _namespaces(
+                self._root, encoding, default_namespace, namespaces
+                )
+            if method == "xml":
+                _serialize_xml(
+                    write, self._root, encoding, qnames, namespaces
+                    )
+            elif method == "html":
+                _serialize_html(
+                    write, self._root, encoding, qnames, namespaces
+                    )
+            else:
+                raise ValueError("unknown method %r" % method)
+
+# --------------------------------------------------------------------
+# serialization support
+
+def _namespaces(elem, encoding, default_namespace, namespaces):
+    # identify namespaces used in this tree
+
+    # maps qnames to *encoded* prefix:local names
+    qnames = {None: None}
+
+    # maps uri:s to prefixes
+    candidate_namespaces = _namespace_map.copy()
+    if namespaces:
+        candidate_namespaces.update(namespaces)
+    if default_namespace:
+        candidate_namespaces[default_namespace] = ""
+    used_namespaces = {}
+
+    def encode(text):
+        return text.encode(encoding)
+
+    def add_qname(qname):
+        if qname in qnames:
+            return
+
+        # calculate serialized qname representation
+        try:
+            if qname.uri is not None:
+                uri = qname.uri
+                prefix = used_namespaces.get(uri, None)
+                if prefix is None:
+                    prefix = candidate_namespaces.get(uri, None)
+                    if prefix is None:
+                        prefix = "ns%d" % len(used_namespaces)
+                    if prefix != "xml":
+                        used_namespaces[uri] = prefix
+                if prefix:
+                    qnames[qname] = encode("%s:%s" % (prefix, qname.name))
+                else:
+                    qnames[qname] = encode(qname.name)
+            else:
+                # XXX: What happens with undefined namespace?
+                qnames[qname] = encode(qname.name)
+        except TypeError:
+            _raise_serialization_error(qname)
+
+    # populate qname and namespaces table
+    if isinstance(elem, Element):
+        for elem in elem.iter():
+            if isinstance(elem, Element):
+                tag = elem.tag
+                if isinstance(tag, QName):
+                    add_qname(tag)
+                elif isinstance(tag, basestring):
+                    add_qname(QName(tag))
+                elif tag is not None:
+                    _raise_serialization_error(tag)
+
+                for key in elem.keys():
+                    if isinstance(key, QName):
+                        add_qname(key)
+                    elif isinstance(key, basestring):
+                        add_qname(QName(key))
+                    elif key is not None:
+                        _raise_serialization_error(key)
+
+    return qnames, used_namespaces
+
+def _serialize_xml(write, elem, encoding, qnames, namespaces):
+    if isinstance(elem, Element):
+        tag = qnames[elem.tag]
+
+        if tag is not None:
+            write("<" + tag)
+
+            if elem.attrib:
+                items = elem.attrib.items()
+                items.sort(key=lambda x: x[0])
+                for k, v in items:
+                    k = qnames[k]
+                    if isinstance(v, QName):
+                        v = qnames[v]
+                    else:
+                        v = _escape_attrib(v, encoding)
+                    write(' ' + k + '="' + v + '"')
+            if namespaces:
+                items = namespaces.items()
+                items.sort(key=lambda x: x[1]) # sort on prefix
+                for v, k in items:
+                    if k:
+                        k = ":" + k
+                    write(" xmlns%s=\"%s\"" % (
+                        k.encode(encoding),
+                        _escape_attrib(v, encoding)
+                        ))
+            if len(elem):
+                write(">")
+                for e in elem:
+                    _serialize_xml(write, e, encoding, qnames, None)
+                write("</" + tag + ">")
+            else:
+                write(" />")
+
+        else:
+            for e in elem:
+                _serialize_xml(write, e, encoding, qnames, None)
+
+    elif isinstance(elem, Comment):
+        write("<!--%s-->" % _escape_cdata(elem.text, encoding))
+
+    elif isinstance(elem, ProcessingInstruction):
+        text = _escape_cdata(elem.target, encoding)
+        if elem.text is not None:
+            text += ' ' + _escape_cdata(elem.text, encoding)
+        write("<?%s?>" % text)
+
+    else:
+        write(_escape_cdata(unicode(elem), encoding))
+
+HTML_EMPTY = set(("area", "base", "basefont", "br", "col", "frame", "hr",
+                  "img", "input", "isindex", "link", "meta" "param"))
+
+def _serialize_html(write, elem, encoding, qnames, namespaces):
+    if isinstance(elem, Element):
+        tag = qnames[elem.tag]
+
+        if tag is not None:
+            write("<" + tag)
+
+            if elem.attrib:
+                items = elem.attrib.items()
+                items.sort(key=lambda x: x[0])
+                for k, v in items:
+                    k = qnames[k]
+                    if isinstance(v, QName):
+                        v = qnames[v]
+                    else:
+                        v = _escape_attrib(v, encoding)
+                    # FIXME: handle boolean attributes
+                    write(' ' + k + '="' + v + '"')
+            if namespaces:
+                items = namespaces.items()
+                items.sort(key=lambda x: x[1]) # sort on prefix
+                for v, k in items:
+                    if k:
+                        k = ":" + k
+                    write(" xmlns%s=\"%s\"" % (
+                        k.encode(encoding),
+                        _escape_attrib(v, encoding)
+                        ))
+            write(">")
+
+            if tag.lower() in ('script', 'style'):
+                write(_encode(''.join(elem.itertext()), encoding))
+            else:
+                for e in elem:
+                    _serialize_html(write, e, encoding, qnames, None)
+
+            if tag not in HTML_EMPTY:
+                write("</" + tag + ">")
+
+        else:
+            for e in elem:
+                _serialize_html(write, e, encoding, qnames, None)
+
+    elif isinstance(elem, Comment):
+        write("<!--%s-->" % _escape_cdata(elem.text, encoding))
+
+    elif isinstance(elem, ProcessingInstruction):
+        text = _escape_cdata(elem.target, encoding)
+        if elem.text is not None:
+            text += ' ' + _escape_cdata(elem.text, encoding)
+        write("<?%s?>" % text)
+
+    else:
+        write(_escape_cdata(elem, encoding))
+
+def _serialize_text(write, elem, encoding):
+    for part in elem.itertext():
+        write(part.encode(encoding))
+
+##
+# Registers a namespace prefix.  The registry is global, and any
+# existing mapping for either the given prefix or the namespace URI
+# will be removed.
+#
+# @param prefix Namespace prefix.
+# @param uri Namespace uri.  Tags and attributes in this namespace
+#     will be serialized with the given prefix, if at all possible.
+# @raise ValueError If the prefix is reserved, or is otherwise
+#     invalid.
+
+def register_namespace(prefix, uri):
+    import re
+    if re.match("ns\d+$", prefix):
+        raise ValueError("Prefix format reserved for internal use")
+    for k, v in _namespace_map.items():
+        if k == uri or v == prefix:
+            del _namespace_map[k]
+    _namespace_map[uri] = prefix
+
+_namespace_map = {
+    # "well-known" namespace prefixes
+    "http://www.w3.org/XML/1998/namespace": "xml",
+    "http://www.w3.org/1999/xhtml": "html",
+    "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
+    "http://schemas.xmlsoap.org/wsdl/": "wsdl",
+    # xml schema
+    "http://www.w3.org/2001/XMLSchema": "xs",
+    "http://www.w3.org/2001/XMLSchema-instance": "xsi",
+    # dublic core
+    "http://purl.org/dc/elements/1.1/": "dc",
+}
+
+def _raise_serialization_error(text):
+    raise TypeError(
+        "cannot serialize %r (type %s)" % (text, type(text).__name__)
+        )
+
+def _encode(text, encoding):
+    try:
+        return text.encode(encoding, "xmlcharrefreplace")
+    except (TypeError, AttributeError):
+        _raise_serialization_error(text)
+
+def _escape_cdata(text, encoding):
+    # escape character data
+    try:
+        # it's worth avoiding do-nothing calls for strings that are
+        # shorter than 500 character, or so.  assume that's, by far,
+        # the most common case in most applications.
+        if "&" in text:
+            text = text.replace("&", "&amp;")
+        if "<" in text:
+            text = text.replace("<", "&lt;")
+        if ">" in text:
+            text = text.replace(">", "&gt;")
+        return text.encode(encoding, "xmlcharrefreplace")
+    except (TypeError, AttributeError):
+        _raise_serialization_error(text)
+
+def _escape_attrib(text, encoding):
+    # escape attribute value
+    try:
+        if "&" in text:
+            text = text.replace("&", "&amp;")
+        if "<" in text:
+            text = text.replace("<", "&lt;")
+        if ">" in text:
+            text = text.replace(">", "&gt;")
+        if "\"" in text:
+            text = text.replace("\"", "&quot;")
+        if "\n" in text:
+            text = text.replace("\n", "&#10;")
+        return text.encode(encoding, "xmlcharrefreplace")
+    except (TypeError, AttributeError):
+        _raise_serialization_error(text)
+
+# --------------------------------------------------------------------
+
+##
+# Generates a string representation of an XML element, including all
+# subelements.
+#
+# @param element An Element instance.
+# @return An encoded string containing the XML data.
+# @defreturn string
+
+def tostring(element, encoding=None, method=None):
+    class dummy:
+        pass
+    data = []
+    file = dummy()
+    file.write = data.append
+    ElementTree(element).write(file, encoding, method=method)
+    return "".join(data)
+
+##
+# Generates a string representation of an XML element, including all
+# subelements.  The string is returned as a sequence of string fragments.
+#
+# @param element An Element instance.
+# @return A sequence object containing the XML data.
+# @defreturn sequence
+# @since 1.3
+
+def tostringlist(element, encoding=None):
+    class dummy:
+        pass
+    data = []
+    file = dummy()
+    file.write = data.append
+    ElementTree(element).write(file, encoding)
+    # FIXME: merge small fragments into larger parts
+    return data
+
+##
+# Writes an element tree or element structure to sys.stdout.  This
+# function should be used for debugging only.
+# <p>
+# The exact output format is implementation dependent.  In this
+# version, it's written as an ordinary XML file.
+#
+# @param elem An element tree or an individual element.
+
+def dump(elem):
+    # debugging
+    import sys
+    if not isinstance(elem, ElementTree):
+        elem = ElementTree(elem)
+    elem.write(sys.stdout)
+    tail = elem.getroot().tail
+    if not tail or tail[-1] != "\n":
+        sys.stdout.write("\n")
+
+# --------------------------------------------------------------------
+# parsing
+
+##
+# Parses an XML document into an element tree.
+#
+# @param source A filename or file object containing XML data.
+# @param parser An optional parser instance.  If not given, the
+#     standard {@link XMLParser} parser is used.
+# @return An ElementTree instance
+
+def parse(source, parser=None):
+    tree = ElementTree()
+    tree.parse(source, parser)
+    return tree
+
+##
+# Parses an XML document into an element tree incrementally, and reports
+# what's going on to the user.
+#
+# @param source A filename or file object containing XML data.
+# @param events A list of events to report back.  If omitted, only "end"
+#     events are reported.
+# @param parser An optional parser instance.  If not given, the
+#     standard {@link XMLParser} parser is used.
+# @return A (event, elem) iterator.
+
+def iterparse(source, events=None, parser=None):
+    if not hasattr(source, "read"):
+        source = open(source, "rb")
+    if not parser:
+        parser = XMLParser(target=TreeBuilder())
+    return _IterParseIterator(source, events, parser)
+
+class _IterParseIterator(object):
+
+    def __init__(self, source, events, parser):
+        self._file = source
+        self._events = []
+        self._index = 0
+        self.root = self._root = None
+        self._parser = parser
+        # wire up the parser for event reporting
+        parser = self._parser._parser
+        append = self._events.append
+        if events is None:
+            events = ["end"]
+        for event in events:
+            if event == "start":
+                try:
+                    parser.ordered_attributes = 1
+                    parser.specified_attributes = 1
+                    def handler(tag, attrib_in, event=event, append=append,
+                                start=self._parser._start_list):
+                        append((event, start(tag, attrib_in)))
+                    parser.StartElementHandler = handler
+                except AttributeError:
+                    def handler(tag, attrib_in, event=event, append=append,
+                                start=self._parser._start):
+                        append((event, start(tag, attrib_in)))
+                    parser.StartElementHandler = handler
+            elif event == "end":
+                def handler(tag, event=event, append=append,
+                            end=self._parser._end):
+                    append((event, end(tag)))
+                parser.EndElementHandler = handler
+            elif event == "start-ns":
+                def handler(prefix, uri, event=event, append=append):
+                    try:
+                        uri = uri.encode("ascii")
+                    except UnicodeError:
+                        pass
+                    append((event, (prefix or "", uri)))
+                parser.StartNamespaceDeclHandler = handler
+            elif event == "end-ns":
+                def handler(prefix, event=event, append=append):
+                    append((event, None))
+                parser.EndNamespaceDeclHandler = handler
+
+    def next(self):
+        while 1:
+            try:
+                item = self._events[self._index]
+            except IndexError:
+                if self._parser is None:
+                    self.root = self._root
+                    raise StopIteration
+                # load event buffer
+                del self._events[:]
+                self._index = 0
+                data = self._file.read(16384)
+                if data:
+                    self._parser.feed(data)
+                else:
+                    self._root = self._parser.close()
+                    self._parser = None
+            else:
+                self._index = self._index + 1
+                return item
+
+    def __iter__(self):
+        return self
+
+##
+# Parses an XML document from a string constant.  This function can
+# be used to embed "XML literals" in Python code.
+#
+# @param source A string containing XML data.
+# @param parser An optional parser instance.  If not given, the
+#     standard {@link XMLParser} parser is used.
+# @return An Element instance.
+# @defreturn Element
+
+def XML(text, parser=None):
+    if not parser:
+        parser = XMLParser(target=TreeBuilder())
+    parser.feed(text)
+    return parser.close()
+
+##
+# Parses an XML document from a string constant, and also returns
+# a dictionary which maps from element id:s to elements.
+#
+# @param source A string containing XML data.
+# @param parser An optional parser instance.  If not given, the
+#     standard {@link XMLParser} parser is used.
+# @return A tuple containing an Element instance and a dictionary.
+# @defreturn (Element, dictionary)
+
+def XMLID(text, parser=None):
+    if not parser:
+        parser = XMLParser(target=TreeBuilder())
+    parser.feed(text)
+    tree = parser.close()
+    ids = {}
+    for elem in tree.getiterator():
+        id = elem.get("id")
+        if id:
+            ids[id] = elem
+    return tree, ids
+
+##
+# Parses an XML document from a string constant.  Same as {@link #XML}.
+#
+# @def fromstring(text)
+# @param source A string containing XML data.
+# @return An Element instance.
+# @defreturn Element
+
+fromstring = XML
+
+##
+# Parses an XML document from a sequence of string fragments.
+#
+# @param sequence A list or other sequence containing XML data fragments.
+# @param parser An optional parser instance.  If not given, the
+#     standard {@link XMLParser} parser is used.
+# @return An Element instance.
+# @defreturn Element
+# @since 1.3
+
+def fromstringlist(sequence, parser=None):
+    if not parser:
+        parser = XMLParser(target=TreeBuilder())
+    for text in sequence:
+        parser.feed(text)
+    return parser.close()
+
+# --------------------------------------------------------------------
+
+##
+# Generic element structure builder.  This builder converts a sequence
+# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
+# #TreeBuilder.end} method calls to a well-formed element structure.
+# <p>
+# You can use this class to build an element structure using a custom XML
+# parser, or a parser for some other XML-like format.
+#
+# @param element_factory Optional element factory.  This factory
+#    is called to create new Element instances, as necessary.
+
+class TreeBuilder(object):
+
+    def __init__(self, element_factory=None):
+        self._data = [] # data collector
+        self._elem = [] # element stack
+        self._last = None # last element
+        if element_factory is None:
+            element_factory = Element
+        self._factory = element_factory
+
+    ##
+    # Flushes the builder buffers, and returns the toplevel document
+    # element.
+    #
+    # @return An Element instance.
+    # @defreturn Element
+
+    def close(self):
+        assert len(self._elem) == 0, "missing end tags"
+        assert self._last is not None, "missing toplevel element"
+        return self._last
+
+    def _flush(self):
+        if self._data:
+            text = "".join(self._data)
+            self._elem[-1].append(text)
+            self._data = []
+
+    ##
+    # Adds text to the current element.
+    #
+    # @param data A string.  This should be either an 8-bit string
+    #    containing ASCII text, or a Unicode string.
+
+    def data(self, data):
+        self._data.append(data)
+
+    ##
+    # Opens a new element.
+    #
+    # @param tag The element name.
+    # @param attrib A dictionary containing element attributes.
+    # @return The opened element.
+    # @defreturn Element
+
+    def start(self, tag, attrs):
+        self._flush()
+        self._last = elem = self._factory(tag, attrs)
+        if self._elem:
+            self._elem[-1].append(elem)
+        self._elem.append(elem)
+        return elem
+
+    ##
+    # Closes the current element.
+    #
+    # @param tag The element name.
+    # @return The closed element.
+    # @defreturn Element
+
+    def end(self, tag):
+        self._flush()
+        self._last = self._elem.pop()
+        assert self._last.tag == tag,\
+               "end tag mismatch (expected %s, got %s)" % (
+                   self._last.tag, tag)
+        return self._last
+
+##
+# Element structure builder for XML source data, based on the
+# <b>expat</b> parser.
+#
+# @keyparam target Target object.  If omitted, the builder uses an
+#     instance of the standard {@link #TreeBuilder} class.
+# @keyparam html Predefine HTML entities.  This flag is not supported
+#     by the current implementation.
+# @keyparam encoding Optional encoding.  If given, the value overrides
+#     the encoding specified in the XML file.
+# @see #ElementTree
+# @see #TreeBuilder
+
+class XMLParser(object):
+
+    def __init__(self, html=0, target=None, encoding=None):
+        try:
+            from xml.parsers import expat
+        except ImportError:
+            raise ImportError(
+                "No module named expat; use SimpleXMLTreeBuilder instead"
+                )
+        parser = expat.ParserCreate(encoding, "}")
+        if target is None:
+            target = TreeBuilder()
+        # underscored names are provided for compatibility only
+        self.parser = self._parser = parser
+        self.target = self._target = target
+        self._error = expat.error
+        self._names = {} # name memo cache
+        # callbacks
+        parser.DefaultHandlerExpand = self._default
+        parser.StartElementHandler = self._start
+        parser.EndElementHandler = self._end
+        parser.CharacterDataHandler = self._data
+        # let expat do the buffering, if supported
+        try:
+            self._parser.buffer_text = 1
+        except AttributeError:
+            pass
+        # use new-style attribute handling, if supported
+        try:
+            self._parser.ordered_attributes = 1
+            self._parser.specified_attributes = 1
+            parser.StartElementHandler = self._start_list
+        except AttributeError:
+            pass
+        self._doctype = None
+        self.entity = {}
+        try:
+            self.version = "Expat %d.%d.%d" % expat.version_info
+        except AttributeError:
+            pass # unknown
+
+    def _raiseerror(self, value):
+        err = ParseError(value)
+        err.code = value.code
+        err.position = value.lineno, value.offset
+        raise err
+
+    def _fixname(self, key):
+        # expand qname, and convert name string to ascii, if possible
+        if key in self._names:
+            return self._names[key].copy()
+        if '}' in key:
+            uri, name = key.split('}', 1)
+            name = QName(name, uri)
+        else:
+            name = QName(key)
+        self._names[key] = name
+        return name
+
+    def _start(self, tag, attrib_in):
+        fixname = self._fixname
+        tag = fixname(tag)
+        attrib = {}
+        for key, value in attrib_in.items():
+            attrib[fixname(key)] = value
+        return self.target.start(tag, attrib)
+
+    def _start_list(self, tag, attrib_in):
+        fixname = self._fixname
+        tag = fixname(tag)
+        attrib = {}
+        if attrib_in:
+            for i in range(0, len(attrib_in), 2):
+                attrib[fixname(attrib_in[i])] = attrib_in[i+1]
+        return self.target.start(tag, attrib)
+
+    def _data(self, text):
+        return self.target.data(text)
+
+    def _end(self, tag):
+        return self.target.end(self._fixname(tag))
+
+    def _default(self, text):
+        prefix = text[:1]
+        if prefix == "&":
+            # deal with undefined entities
+            try:
+                self.target.data(self.entity[text[1:-1]])
+            except KeyError:
+                from xml.parsers import expat
+                err = expat.error(
+                    "undefined entity %s: line %d, column %d" %
+                    (text, self._parser.ErrorLineNumber,
+                    self._parser.ErrorColumnNumber)
+                    )
+                err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
+                err.lineno = self._parser.ErrorLineNumber
+                err.offset = self._parser.ErrorColumnNumber
+                raise err
+        elif prefix == "<" and text[:9] == "<!DOCTYPE":
+            self._doctype = [] # inside a doctype declaration
+        elif self._doctype is not None:
+            # parse doctype contents
+            if prefix == ">":
+                self._doctype = None
+                return
+            text = text.strip()
+            if not text:
+                return
+            self._doctype.append(text)
+            n = len(self._doctype)
+            if n > 2:
+                type = self._doctype[1]
+                if type == "PUBLIC" and n == 4:
+                    name, type, pubid, system = self._doctype
+                elif type == "SYSTEM" and n == 3:
+                    name, type, system = self._doctype
+                    pubid = None
+                else:
+                    return
+                if pubid:
+                    pubid = pubid[1:-1]
+                if hasattr(self.target, "doctype"):
+                    self.target.doctype(name, pubid, system[1:-1])
+                self._doctype = None
+
+    ##
+    # Feeds data to the parser.
+    #
+    # @param data Encoded data.
+
+    def feed(self, data):
+        try:
+            self._parser.Parse(data, 0)
+        except self._error, v:
+            self._raiseerror(v)
+
+    ##
+    # Finishes feeding data to the parser.
+    #
+    # @return An element structure.
+    # @defreturn Element
+
+    def close(self):
+        try:
+            self._parser.Parse("", 1) # end of data
+        except self._error, v:
+            self._raiseerror(v)
+        tree = self.target.close()
+        del self.target, self._parser # get rid of circular references
+        return tree
+