在Python

时间:2018-05-04 12:21:21

标签: python xml serialization

这有点奇怪,但我没有找到任何关于这样(似乎)流行话题的有用信息,比如Python中的XML序列化!我是Python的新手,所以请原谅我愚蠢的问题。 我有一节课:

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

我想得到它的XML字符串表示,如:

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

我尝试使用lxml.etree.tostring,但它说Result无法序列化。我想我错过了什么......

1 个答案:

答案 0 :(得分:1)

我制作了一个简单的lib PySXM,可能会帮助您。如果您需要更多信息,请随时联系我

使用PySXM,您将可以执行以下操作:

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。

也可以使用 DataComplexType