简体   繁体   中英

Python object serialization to XML & deserialization from XML

How I can serialize instance of class to XML file and deserialize back?


For example.

I have class "Cat":

class Cat:
    __name=''
    __age=0
    __tail_length=0
    __weight=0

    def __init__(self, name, age, tail_length, weight):
        self.__name=name
        self.__age=age
        self.__tail_length=tail_length
        self.__weight=weight

Is possible make that?

timon=Cat(name='Timon', age=3, tail_length=20, weight=18)
magic_xml_serializer.serialize(destfile='cat-timon.xml', obj=timon)
del(timon)
timon=magic_xml_serializer.deserialize(sourcefile='cat-timon.xml')
print ('yes','no')[type(timon)=='Cat'] #yes

If it's possible to do, please write me how. Or just give me link with examples of code. Thanks!

PS Python version 2.7

you can use spyne for getting xml output over a server (RPC). spyne is excellent for soap if that is what you want (looking at your C# .NET background)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM