Commits

Mads Sülau Valstorp Jørgensen  committed 8273ecc

Made a XMLEmitter.

  • Participants
  • Parent commits 8ba536f

Comments (0)

Files changed (1)

File piston/emitters.py

 from django.db.models.query import QuerySet
 from django.db.models import Model
 from django.utils import simplejson
+from django.utils.xmlutils import SimplerXMLGenerator
+from django.utils.encoding import smart_unicode
 from django.core.serializers.json import DateTimeAwareJSONEncoder
 
+try:
+    import cStringIO as StringIO
+except ImportError:
+    import StringIO
+
 class Emitter(object):
     def __init__(self, payload, typemapper):
         self.typemapper = typemapper
             return YAMLEmitter, 'text/plain'
     
 class XMLEmitter(Emitter):
-    pass
-    
+    def _to_xml(self, xml, data):
+        if isinstance(data, (list, tuple)):
+            for item in data:
+                self._to_xml(xml, item)
+        elif isinstance(data, dict):
+            for key, value in data.iteritems():
+                xml.startElement(key, {})
+                self._to_xml(xml, value)
+                xml.endElement(key)
+        elif data:
+            xml.characters(smart_unicode(data))
+
+    def render(self):
+        stream = StringIO.StringIO()
+        
+        xml = SimplerXMLGenerator(stream, "utf-8")
+        xml.startDocument()
+        xml.startElement("response", {})
+        
+        self._to_xml(xml, self.construct())
+        
+        xml.endElement("response")
+        xml.endDocument()
+        
+        return stream.getvalue()
+
 class JSONEmitter(Emitter):
     # TODO: callback functions
     def render(self):