首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一个更好的带有嵌套类的Python 3 XML解析器(dicttoxml)

一个更好的带有嵌套类的Python 3 XML解析器(dicttoxml)
EN

Stack Overflow用户
提问于 2020-07-07 17:31:04
回答 1查看 327关注 0票数 0

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

代码语言:javascript
复制
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:

代码语言:javascript
复制
<person> 
   <firstname>John</firstname>
   <lastname>Doe</lastname>
   <homeAddress>
        <city>Dallas</city>
        <state>TX</state>
   </homeAddress>
</person>

在指令函数中出现的错误:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-07 17:47:29

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

代码语言:javascript
复制
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'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62780800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档