更好的 XML 解析器 Python 3 嵌套 类 (dicttoxml)

A better XML Parser for Python 3 with nested classes (dicttoxml)

这实际上是这个问题的第 2 部分: 在那个问题中,我没有指定我可能嵌套了 类。酸洗工和编组工没有生产出我要找的 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

将地址 class 添加到人 class 意味着 Vars() 无法再将 class 转换为密钥对字典。作为解决方法,您可以导入 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'