XML 更好的 Python 序列化器 3

A better XML Serializer for Python 3

我试过xml_marshaller如下:

from xml_marshaller import xml_marshaller

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

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

上面的输出是:

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>'

格式化后看起来像这样,在我看来这是最丑陋的 XML 可能:

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>'

b 和引号在那里做什么?也许意味着“二进制”?这真的是数据的一部分,还是只是将其打印到控制台的副作用?

是否有任何 Python 3 库可以像这样创建更接近“人类”的东西:

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

我正在寻找接近 .NET 创建的内容(请参阅 http://mylifeismymessage.net/xml-serializerdeserializer/

请不要告诉我尝试 JSON 或 YAML,这不是问题所在。例如,我可能想通过 XSLT 运行 文件。

2天后更新:

我喜欢彼得霍夫曼的回答: 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)

给出错误:

TypeError: Type 'Person' cannot be serialized.

在我的场景中,我可能已经有一个 class 结构,并且不想切换到他们正在做的方式你可以序列化我的“人”吗 class?

输出将 xml 显示为字典的原因很可能是因为属性没有对 class 的引用。您应该考虑使用 self. 并在 __init__ 函数中赋值。

class Person:
    def __init__(self):
        self.firstName = "John"
        self.lastName = "Doe"

有很多方法可以将对象转换为 XML。但是请尝试使用包 dicttoxml。顾名思义,您需要将对象转换为字典,这可以使用 vars().

来完成

完整解决方案:

from dicttoxml import dicttoxml

class Person:
    def __init__(self):
        self.firstName = "John"
        self.lastName = "Doe"

person = vars(Person()) # vars is pythonic way of converting to dictionary
xml = dicttoxml(person, attr_type=False, custom_root='Person') # set root node to Person
print(xml)

输出:

b'<?xml version="1.0" encoding="UTF-8" ?><Person><firstName>John</firstName><lastName>Doe</lastName></Person>'

如果你想很好地格式化 XML,那么你可以使用内置的 xml.dom.minidom.parseString 库。

from dicttoxml import dicttoxml
from xml.dom.minidom import parseString

class Person:
    def __init__(self):
        self.firstName = "John"
        self.lastName = "Doe"

person = vars(Person()) # vars is pythonic way of converting to dictionary
xml = dicttoxml(person, attr_type=False, custom_root='Person') # set root node to Person
print(xml)

dom = parseString(xml)
print(dom.toprettyxml())

输出:

<?xml version="1.0" ?>
<Person>
        <firstName>John</firstName>
        <lastName>Doe</lastName>
</Person

请查看文档 https://pypi.org/project/dicttoxml/,因为您可以传递额外的参数来改变输出。