changeset 5:9b72cb3ef3c9

Support strings a children. * emeraldtree/ElementTree.py - Only allow Node and basestring as children of an Element. - Check type during iteration. - Serialize all non-Node objects as text. * emeraldtree/tests/test_ElementTree.py: Add tests.
author Bastian Blank <bblank@thinkmo.de>
date Sat, 31 May 2008 15:40:43 +0200
parents 705fc192cd9d
children ced434b6bf72
files emeraldtree/ElementTree.py emeraldtree/tests/test_ElementTree.py
diffstat 2 files changed, 12 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- a/emeraldtree/ElementTree.py	Sat May 31 15:19:09 2008 +0200
+++ b/emeraldtree/ElementTree.py	Sat May 31 15:40:43 2008 +0200
@@ -165,9 +165,7 @@
 # @defreturn flag
 
 def iselement(element):
-    # FIXME: not sure about this; might be a better idea to look
-    # for tag/attrib/text attributes
-    return isinstance(element, Element) or hasattr(element, "tag")
+    return isinstance(element, (Node, basestring))
 
 class Node(object):
     """
@@ -485,7 +483,11 @@
         if tag is None or self.tag == tag:
             yield self
         for e in self._children:
-            for e in e.iter(tag):
+            if isinstance(e, Element):
+                for e in e.iter(tag):
+                    yield e
+            # TODO
+            elif isinstance(e, Node):
                 yield e
 
     # compatibility (FIXME: preserve list behaviour too? see below)
@@ -892,7 +894,10 @@
                 if text:
                     write(_escape_cdata(text, encoding))
                 for e in elem:
-                    _serialize_xml(write, e, encoding, qnames, None)
+                    if isinstance(e, Node):
+                        _serialize_xml(write, e, encoding, qnames, None)
+                    else:
+                        write(_escape_cdata(unicode(e), encoding))
                 write("</" + tag + ">")
             else:
                 write(" />")
--- a/emeraldtree/tests/test_ElementTree.py	Sat May 31 15:19:09 2008 +0200
+++ b/emeraldtree/tests/test_ElementTree.py	Sat May 31 15:40:43 2008 +0200
@@ -18,3 +18,5 @@
     assert serialize(elem) == '<a><b /></a>'
     elem.append(Element('c'))
     assert serialize(elem) == '<a><b /><c /></a>'
+    elem.append('d')
+    assert serialize(elem) == '<a><b /><c />d</a>'