A better XML Serializer for Python 3

╄→尐↘猪︶ㄣ 提交于 2020-06-29 06:42:18

问题


I tried xml_marshaller as follows:

from xml_marshaller import xml_marshaller

class Person:
    firstName = "John"
    lastName = "Doe"

person1 = Person()
strXmlPerson = xml_marshaller.dumps(person1);
print(strXmlPerson)

The output from above is:

b'<marshal><object id="i2" module="__main__" class="Person"><tuple/><dictionary id="i3"><string>firstName</string><string>John</string><string>lastName</string><string>Doe</string></dictionary></object></marshal>'

which when formatted looks like this, which in my opinion is the ugliest XML possible:

b'<marshal>
    <object id="i2" module="__main__" class="Person">
        <tuple/>
        <dictionary id="i3">
            <string>firstName</string>
            <string>John</string>
            <string>lastName</string>
            <string>Doe</string>
        </dictionary>
    </object>
</marshal>'

What is the b and quotes doing there? Means "binary" maybe? Is that really part of the data, or just a side effect of printing it to the console?

Is there any Python 3 library that will create something more closer to "human" like this:

<Person> 
   <firstname>John</firstname>
   <lastname>Doe<lastname>
</Person> 

I'm looking for something close to what .NET creates (see http://mylifeismymessage.net/xml-serializerdeserializer/.

Please don't tell me try JSON or YAML, that's not the question. I might want to run the file through XSLT for example.

Update 2 days later:

I like the Peter Hoffman answer here: How can I convert XML into a Python object?

person1 = Person("John", "Doe") #strXmlPerson = xml_marshaller.dumps(person1); person = objectify.Element("Person") strXmlPerson = lxml.etree.tostring(person1, pretty_print=True) print(strXmlPerson)

gives error:

TypeError: Type 'Person' cannot be serialized.

In my scenario I might already have a class structure, and don't want to switch to they way they are doing it You can I serialize my "Person" class?

来源:https://stackoverflow.com/questions/62604159/a-better-xml-serializer-for-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!