Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a Python object into XML?

I am looking to convert a Python object into XML data. I've tried lxml, but eventually had to write custom code for saving my object as xml which isn't perfect.

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.

like image 904
mdob Avatar asked Nov 26 '22 19:11

mdob


1 Answers

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.

like image 159
Mark Byers Avatar answered Dec 10 '22 14:12

Mark Byers