0

It's a bit strange, but I didn't find any useful information on such (seemed) popular topic like XML serialization in Python! I'm new to Python, so forgive me dumb question in case it is. I have a class:

class Purchase:
    @property
    def shortPurchaseDesc(self):
        return self._shortPurchaseDesc

    @shortPurchaseDesc.setter
    def shortPurchaseDesc(self, value):
        self._shortPurchaseDesc = value;

class Result():

    @property
    def resultCode(self):
        return self._resultCode;

    @resultCode.setter
    def resultCode(self, value):
        self._resultCode = value

    _purchase = Purchase()

    @property
    def purchase(self):
        return self._purchase;

    @purchase.setter
    def purchase(self, value):
        self._purchase = value

And I want to get the XML string representation of it, something like:

<result>
 <resultCode>2</resultCode>
 <purchase>
  <shortPurchaseDesc>test</shortPurchaseDesc>
 </purchase>
</result>

I've tried to use lxml.etree.tostring, but it says that Result can not be serialized. I think I'm missing something...

3
  • You have to define methods that serialize the content in xml (one per class). Commented May 4, 2018 at 12:51
  • @CristiFati I'm from .NET and we have Serializable attribute there, to mark classes as serializable. Hoped that there are some easy ways here too, historically XML serialization was very popular before JSON. And what kind of functions I have to define? Commented May 4, 2018 at 12:53
  • I'm not aware of such a module (although there's a pretty good chance that it would exist). You have to do a method that serializes the state of one instance. Commented May 4, 2018 at 13:00

1 Answer 1

2

I've made a simple lib PySXM which might help you out. Don't hesitate to hit me up in case you need more info

With PySXM you would have done something like this:

from pysxm import ComplexType

class Purchase(ComplexType):

    def __init__(self, desc):
        self.shortPurchaseDesc = desc


class Result(ComplexType):

    def __init__(self, code, desc):
        self.resultCode = code
        self.purchase = Purchase(desc)


In [2]: result = Result('2', 'test')

In [3]: print(result)
<result>
    <purchase>
        <shortPurchaseDesc>test</shortPurchaseDesc>
    </purchase>
    <resultCode>2</resultCode>
</result>

In [4]: result.xml
Out[4]: <Element result at 0x7f07276edb00>

In [5]: result.save('output.xml')

Voila.

It's possible to use a DataComplexType too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.