Convert python object to XML representation

Share

The application I was working on used a Flash slide show. The configuration on the slide show was done from a xml file. The task was to make this configuration manageable from the Django admin.

I have created a model that represents the elements of the xml file. All I need was a way to convert the python database object to a xml representation.

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save, post_delete
 
from lxml.etree import ElementTree, Element, SubElement
import StringIO
 
class XMLModelWriter:
    def __init__(self, model, file_name):
        self.model = model
        self.file_name = file_name
    def write(self):
        content_type = ContentType.objects.get_for_model(model=self.model)
        try:
            model_class = content_type.model_class()
            object_name = model_class._meta.object_name
            root = Element((object_name + 's').lower())
            element_tree = ElementTree(root)
            for object in model_class.objects.all():
                element = SubElement(root, object_name.lower())
                for field in object._meta.fields:
                    child = SubElement(element, field.name)
                    value = getattr(object, field.name)
                    if value != None:
                        if isinstance(value, models.base.Model):
                            # This field is a foreign key, so save the primary key
                            # of the referring object
                            pk_name = value._meta.pk.name
                            pk_value = getattr(value, pk_name)
                            child.text = unicode(pk_value)
                        else:
                            print value
                            child.text = unicode(value)
            new_file = open(self.file_name, 'w')
            element_tree.write(new_file, pretty_print=True, xml_declaration=True, encoding='utf-8')
        except ContentType.DoesNotExist:
            pass
 
class Item(models.Model):
    picture = models.CharField("Picture", blank=True, max_length=100)
    title = models.CharField("Title", blank=True, max_length=100)
    link = models.URLField("Link", verify_exists=False, blank=True)
    color = models.CharField("Color", blank=True, max_length=100)    
 
    def __unicode__(self):
        return self.title
 
    class Meta:
        verbose_name = "Item"
        verbose_name_plural = "Items"
def item_handler(sender, **kwargs):
    writer = XMLModelWriter(Item, 'D:/test/items.xml')
    writer.write() 
 
post_save.connect(item_handler, sender=Item)
post_delete.connect(item_handler, sender=Item)

ContentType object is used to track all of the models installed, providing a high-level, generic interface for working with the models. Item objects are converted to a xml document, each time the user creates or modifies Item objects.

This code requires the lxml python library.

Finally, there’s another very important peculiarity of what does Cialis that brings it so high above its alternatives. It is the only med that is available in two versions – one intended for use on as-needed basis and one intended for daily use. As you might know, Viagra and Levitra only come in the latter of these two forms and should be consumed shortly before expected sexual activity to ensure best effect. Daily Cialis, in its turn, contains low doses of Tadalafil, which allows to build its concentration up in your system gradually over time and maintain it on acceptable levels, which, consequently, makes it possible for you to enjoy sex at any moment without having to time it.

By continuing to use the site, you agree to the use of cookies. More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close