python-3.x - 用于 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”类吗?
解决方案
输出将 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/,因为您可以传递其他参数来更改输出。
推荐阅读
- html - 尽管使用简单,媒体查询仍不起作用
- npm - Vue-Cli3 和最近的 Node-Sass DoS 咨询:如何用 dart-sass 替换 node-sass?
- sql - 创建函数后我应该 COMMIT 吗?
- python - 检查字符串中的 id 是否存在于另一个列表中
- angular - 如何以角度获取和显示实时用户通知?
- php - PHP颜色未被确认
- dji-sdk - 在姿态模式下以速度移动无人机
- xml - Ansible - XML 命名空间
- google-apps-script - 获取 Gsuite google drive 上的文件夹列表,在 Google Sheet 上按字母顺序列出
- javascript - 在浏览器中打开新标签的问题