简体   繁体   English

Python 如何在对象内序列化 xml 对象

[英]Python how to serialize xml objects within objects

I'm trying to serialize a python object into xml.我正在尝试将 python object 序列化为 xml。 if I use dict2xml package it sort of works.如果我使用 dict2xml package 它有点工作。 Most of the fields in the object serialize to xml but I also have an object within the object that does not. object 中的大多数字段都序列化为 xml 但我在 ZA8CFDE63311C4B66 中也有一个 object 没有。 It also doesn't put the main tags "person".它也没有放置主要标签“人”。

My objects:我的对象:

@dataclass
class Person:
    first_name: str
    last_name: str
    address: Address
    
@dataclass
class Address:
    line1: str
    city: str
    state: str
    zip: str

Returned XML:返回 XML:

<address>Address(line1='line1', city='city1', state='state1', zip='12345')</address>
<first_name>firstname</first_name>
<last_name>lastname</last_name>

code:代码:

dict2xml(person.__dict__)  # <-- person is instantiated Person with data

would like it to return:希望它返回:

<Person>
    <address>
        <line1>line1</line1>
        <city>city1</city>
        <state>state1</state>
        <zip>12345</zip>
    </address>
    <first_name>firstname</first_name>
    <last_name>lastname</last_name>
</Person>

Thoughts on how I can get the objects into my desired xml format?关于如何将对象转换为所需的 xml 格式的想法?

The dict2xml module does not seem to provide any way to define how it should turn your class objects into dictionaries. dict2xml模块似乎没有提供任何方法来定义它应该如何将您的 class 对象转换为字典。 So you have to do this yourself at all levels so that what you pass to the module consists only of standard Python dicts and lists.因此,您必须自己在各个级别执行此操作,以便传递给模块的内容仅包含标准 Python 字典和列表。

Also, to get the outer <Person> tag, you can utilize the optional wrap parameter.此外,要获取外部<Person>标记,您可以使用可选的wrap参数。 Alternatively, you could create an outer dict with the key Person to get that level from the data itself.或者,您可以使用键Person创建一个外部 dict,以从数据本身获取该级别。

Here are both ways to get the output you desire:以下是获得您想要的 output 的两种方法:

from dataclasses import dataclass
import dict2xml as dict2xml

@dataclass
class Address:
    line1: str
    city: str
    state: str
    zip: str

@dataclass
class Person:
    first_name: str
    last_name: str
    address: Address


person = Person("firstname", "lastname", Address("line1", "city1", "state1", "12345"))

pd = person.__dict__.copy()
pd['address'] = pd['address'].__dict__

print(dict2xml.dict2xml(pd, wrap="Person"))
# OR: print(dict2xml.dict2xml({'Person': pd}))

Result:结果:

<Person>
  <address>
    <city>city1</city>
    <line1>line1</line1>
    <state>state1</state>
    <zip>12345</zip>
  </address>
  <first_name>firstname</first_name>
  <last_name>lastname</last_name>
</Person>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM