views:

88

answers:

2

I've tried lxml and eventually had to write the whole code for saving object as xml which isn't perfect. I suppose there is a neat way to do it but I just can't find it.

I'm looking for something more like pyxser. Unfortunately pyxser xml code looks different from what I need.

For instance I have my own class Person

Class Person:
    name = ""
    age = 0
    ids = []

and I want to covert it into xml code looking like

<Person>
    <name>Mike</name>
    <age> 25 </age>
    <ids>
        <id>1234</id>
        <id>333333</id>
        <id>999494</id>
   </ids>
</Person>

I didn't find any method in lxml.objectify that takes object and returns xml code.

+1  A: 

Best is rather subjective and I'm not sure it's possible to say what's best without knowing more about your requirements. However Gnosis has previously been recommended for serializing Python objects to XML so you might want to start with that.

From the Gnosis homepage:

Gnosis Utils contains several Python modules for XML processing, plus other generally useful tools:

  • xml.pickle (serializes objects to/from XML)
  • API compatible with the standard pickle module)
  • xml.objectify (turns arbitrary XML documents into Python objects)
  • xml.validity (enforces XML validity constraints via DTD or Schema)
  • xml.indexer (full text indexing/searching)
  • many more...

Another option is lxml.objectify.

Mark Byers
A: 

tried xml.pickle and the result is similar to pyxser. The output looks like this

<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="__main__" class="Person" id="176431404">
<attr name="age" type="numeric" value="25" />
<attr name="name" type="string" value="mike" />
<attr name="ids" type="list" id="176666348" >
  <item type="numeric" value="1234" />
  <item type="numeric" value="1343" />
  <item type="numeric" value="134324" />
  <item type="numeric" value="1234213" />
</attr>
</PyObject>

which is hard to read and parse later. How can I create an xml code the way I need it?

Mike Dobrzanski