首页 > 解决方案 > 用于 Python 3 的更好的 XML 序列化器

问题描述

我尝试了 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天后更新:

我喜欢 Peter Hoffman 的回答: 如何将 XML 转换为 Python 对象?

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.

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

标签: python-3.xxmlxmlserializer

解决方案


输出将 xml 显示为字典的原因很可能是因为属性没有对类的引用。您应该考虑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/,因为您可以传递其他参数来更改输出。


推荐阅读