适用于 Python 3 的更好的 XML 序列化程序 [英] A better XML Serializer for Python 3

查看:28
本文介绍了适用于 Python 3 的更好的 XML 序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过 xml_marshaller 如下:

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)

上面的输出是:

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:

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

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

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?

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

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

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

我正在寻找接近于 .NET 创建的东西(参见 http://mylifeismymessage.net/xml-serializerdeserializer/.

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

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

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.

两天后更新:

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

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)

给出错误:

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?

推荐答案

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

The reason the output is showing xml as a dictionary is most likely because the properties don't have a reference to the class. You should consider using self. and assigning values within a __init__ function.

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

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

There are many ways to convert an object to XML. However try using the package dicttoxml. As the name suggest you'll need to convert object to a dictionary, which can be done using 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 库.

If you want to format the XML nicely, then you can use the built in xml.dom.minidom.parseString library.

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/ 作为你可以传递额外的参数来改变输出.

Do check out the documentation https://pypi.org/project/dicttoxml/ as you can pass additional arguments to alter the output.

这篇关于适用于 Python 3 的更好的 XML 序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆