Ropardo Sowftware development company

Experience software development with ROPARDO S.R.L.

RSS Feed
RSS Feed
  • Home
  • About ROPARDO S.R.L
  • Our websites

Convert python object to XML representation

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.

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
Get Shareaholic
Tags: database django PostgreSQL Python xml

 Posted in: Software Development
September 26, 2011 | Ioan Seicean | No Comments

Leave a Reply

 


  • « Previous post
  • Next post »
  • Recent Posts

    • Meet Ropardo at CeBit 2012
    • Installing PyGraphviz on Windows
    • Convert python object to XML representation
    • Liferay Portlet Development
    • Norway Road Show 2011 private meeting invitation
  • Ropardo is Hiring

  • Subscribe

    • Add to Google Reader or Homepage Add to netvibes TopOfBlogs
  • Recent Comments

    • ze_felipe on GWT 2.1 – Uploading a file using the RPC mechanism
    • Artiom on GWT 2.1 – Uploading a file using the RPC mechanism
    • sushant on Installing PyGraphviz on Windows
    • Luis Molina on Connect to an Axis 1 Web Service with Basic Authentication
    • R.Ganesan on Multiple select TreeView in ComboBox
  • Archives

    • February 2012 (1)
    • November 2011 (1)
    • September 2011 (4)
    • July 2011 (3)
    • June 2011 (2)
    • May 2011 (4)
    • April 2011 (4)
    • March 2011 (3)
    • February 2011 (2)
    • January 2011 (2)
    • December 2010 (1)
    • November 2010 (4)
    • October 2010 (4)
    • August 2010 (3)
    • July 2010 (3)
    • June 2010 (6)
    • May 2010 (8)
    • April 2010 (7)
    • March 2010 (9)
    • February 2010 (6)
    • January 2010 (5)
    • December 2009 (7)
    • November 2009 (9)
    • October 2009 (10)
    • September 2009 (14)
    • August 2009 (10)
    • July 2009 (1)
    • June 2009 (1)
    • May 2009 (1)
    • April 2009 (1)
    • March 2009 (1)
    • October 2008 (3)
    • October 2007 (3)
    • July 2007 (4)
    • June 2007 (1)
    • May 2007 (3)
  • Meta

    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.org
  • Categories

    • News (16)
    • Ropardo Team (8)
    • Ropardo Products (6)
      • File Tracking Client (4)
      • iManagement (2)
    • Software Development (83)
      • Microsoft.NET (22)
      • Java (41)
      • Oracle (8)
      • Power Builder (3)
      • Liferay (5)
      • Lotus Notes (9)
      • xWiki (4)
    • System Adminstration (13)
      • Linux (10)
      • Windows (3)
    • Programming (1)
    • Uncategorized (3)
    • Databases (10)
      • MSSQL (5)
      • PostgreeSQL (3)
    • Microsoft.NET (1)
    • Web Development (28)
      • ASP/ASPX (3)
      • Content Management Systems (1)
      • HTML/CSS (5)
      • Javascrip/AJAX (8)
      • PHP (7)
    • Oracle E Business Suite (6)
  • Tags

    .NET ajax blog C# certification client CMS control css database Debugging django Domino Eclipse extension file tracking filter fun gentoo google Hibernate how to html image iManagement import Java javascript jQuery liferay Linux Lotus Notes lotus script Oracle Oracle BI Publisher 11g PHP portal PostgreSQL powerbuilder Python SQL Telerik velocity xml Xwiki

© 2012 ROPARDO s.r.l..

Powered by WordPress. Styled by Ropardo