xml marshal of general (but non Python standard) class

"Martin v. Löwis" martin at v.loewis.de
Sun Mar 27 05:38:06 EST 2005


> In my project, I have container classes holding lists of item classes.
> For example, a container class myLibrary might hold a list of item
> classes myNation and associated variables like myNation.name='USA' and
> myNation.continent='North America'.
> 
> Bottom line, I was hoping to use this structure to marshal the classes
> to xml.

The center question here is: why? To read it back in later? I would
recommend to use pickle instead.

> I'm moderately experienced with Python, but by no means an expert, and
> I'm not an xml pro, either.  Would this project (xml marshal of a new
> class) be worth my time?  If so, what would be best way to proceed?
> Any other thoughts?

As a starting point, you should ask yourself why you want this, and
then how you want the XML to look like. If "any XML" is fine, you
can relatively easy dump an object through marshal.generic:

 >>> class Foo:
...   pass
...
 >>> f=Foo()
 >>> f.name="Hallo"
 >>> f.age=10
 >>>
 >>> xml.marshal.generic.dumps(f)
'<?xml version="1.0"?><marshal><object id="i2" module="__main__" 
class="Foo"><tuple></tuple><dictionary 
id="i3"><string>age</string><int>10</int><string>name</string><string>Hallo</string></dictionary></object></marshal>'

However, the advantage of this format over pickle might be
questionable.

Regards,
Martin



More information about the Python-list mailing list