0

这实际上是这个问题的第 2 部分:A better XML Serializer for Python 3 在那个问题中,我没有指定我可能有嵌套的类。picklers 和 marshallers 没有生成我正在寻找的 XML。

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

class Person:
    def __init__(self, _firstname, _lastname, _address):
        self.firstName = _firstname
        self.lastName = _lastname
        self.homeAddress = _address
class Address:
    def __init__(self, _city, _state):
        self.city = _city
        self.state = _state

address1 = Address("Dallas", "TX")
person1 = Person("John", "Doe", address1)
personDict = vars(person1) # vars is pythonic way of converting to dictionary
xml = dicttoxml(personDict, attr_type=False, custom_root='Person') # set root node to Person
print(xml)
dom = parseString(xml)
xmlFormatted = dom.toprettyxml()
print(xmlFormatted)

所需的 XML:

<person> 
   <firstname>John</firstname>
   <lastname>Doe</lastname>
   <homeAddress>
        <city>Dallas</city>
        <state>TX</state>
   </homeAddress>
</person>

我在 dicttoxml 函数中遇到的错误:

Traceback (most recent call last):
  File "E:/GitHub/NealWalters/PythonEDI/SerializeTest.py", line 19, in <module>
    xml = dicttoxml(personDict, attr_type=False, custom_root='Person') # set root node to Person
  File "E:\Python\Python36\lib\site-packages\dicttoxml.py", line 393, in dicttoxml
    convert(obj, ids, attr_type, item_func, cdata, parent=custom_root), 
  File "E:\Python\Python36\lib\site-packages\dicttoxml.py", line 189, in convert
    return convert_dict(obj, ids, parent, attr_type, item_func, cdata)
  File "E:\Python\Python36\lib\site-packages\dicttoxml.py", line 251, in convert_dict
    val, type(val).__name__)
TypeError: Unsupported data type: <__main__.Address object at 0x000001C94062B0B8> (Address)

Process finished with exit code 1
4

1 回答 1

1

将 Address 类添加到 Person 类意味着 Vars() 不能再将类转换为密钥对字典。作为一种解决方法,您可以导入 json。将对象转换为 json 字符串并将字符串加载为 json 对象。

from dicttoxml import dicttoxml
import json

class Person:
    def __init__(self, _firstname, _lastname, _address):
        self.firstName = _firstname
        self.lastName = _lastname
        self.homeAddress = _address
class Address:
    def __init__(self, _city, _state):
        self.city = _city
        self.state = _state

address1 = Address("Dallas", "TX")
person1 = Person("John", "Doe", address1)
obj = json.loads(json.dumps(person1, default=lambda x: x.__dict__))

xml = dicttoxml(obj, attr_type=False, custom_root='Person'
于 2020-07-07T17:47:29.790 回答