Search code examples
pythonxmldjangodjango-piston

how to change xml element name in django-piston?


I'm new with django-piston and whenever i get/post data to xml, the xml's element is always and < resource >

<response>
<resource>
 <resource>4</resource>
 <resource>0</resource>
 <resource>2011-11-30</resource>
</resource>
<resource>
 <resource>4</resource>
 <resource>4</resource>
 <resource>2011-12-01</resource>
</resource>
<resource>
 <resource>4</resource>
 <resource>0</resource>
 <resource>2011-12-02</resource>
</resource>
<resource>
 <resource>4</resource>
 <resource>0</resource>
 <resource>2011-12-03</resource>
</resource>
<resource>
 <resource>4</resource>
 <resource>0</resource>
 <resource>2011-12-04</resource>
</resource>
</response>

is there a way to change it in the handlers.py? i just want to chage the resource to product and if it possible, can i also put an id to the xml element?


Solution

  • You have to write your own XMLEmitter. Here's one that always uses the tag product instead of resource.

    Making it intelligent requires a bit more work, since models are serialized into dicts in Emitter.construct() method and it's impossible to extend properly. It would be nice to know the original model class in the _to_xml() method and name the element based on the class name.

    from piston.emitters import Emitter, XMLEmitter
    
    class ProductXMLEmitter(XMLEmitter):
        def _to_xml(self, xml, data):
            if isinstance(data, (list, tuple)):
                for item in data:
                    attrs = {}
                    # if item contains id value, use it as an attribute instead
                    if isinstance(item, dict):
                        attrs["id"] = unicode(item.pop("id"))
                    xml.startElement("product", attrs)
                    self._to_xml(xml, item)
                    xml.endElement("product")
            else:
                super(BetterXMLEmitter, self)._to_xml(xml, data)
    
    # replace default XMLEmitter with ours
    Emitter.register('xml', ProductXMLEmitter, 'text/xml; charset=utf-8')
    

    Also, you may want to look at PBS Education's django-piston fork at https://github.com/pbs-education/django-piston. It allows you to customize the output in other ways with PistonViews.