dapper91 / pydantic-xml

python xml for humans
https://pydantic-xml.readthedocs.io
The Unlicense
141 stars 14 forks source link

Question: Is it possible to have an empty container while serializing the model ? #109

Closed muffi-dn closed 8 months ago

muffi-dn commented 10 months ago
class FoobarConfigItems(BaseXmlModel, tag="config-items"):
    name: str | None = element(default=None)

class Foobar(BaseXmlModel):
    name: str | None = element(default=None)
    config_items: FoobarConfigItems | None = element(default=None)

foo = Foobar()
foo.name = "foobar"
foo.config_items = FoobarConfigItems()
print(foo.to_xml())

Is it possible that while serializing the request, i can have the following output

<foobar>
  <name>foo</name>
  <config-items></config-items>

Instead of the usual

<foobar>
  <name>foo</name>
  <config-items>
      <name>None</name> 
 </config-items>

I am aware of the skip_empty argument but it removes the whole element instead of just sub-elements.

Thank you

dapper91 commented 9 months ago

Hi @muffi-dn

Unfortunately there is no way to set skip_empty for a particular element, but starting from 2.2.1 it is possible to set skip_empty for a model. So this code:

class FoobarConfigItems(BaseXmlModel, tag="config-items", skip_empty=True):
    name: str | None = element(default=None)

class Foobar(BaseXmlModel):
    name: str | None = element(default=None)
    config_items: FoobarConfigItems | None = element(default=None)

foo = Foobar()
foo.name = "foobar"
foo.config_items = FoobarConfigItems()
print(foo.to_xml(pretty_print=True).decode())

produces the document you desire:

<Foobar>
  <name>foobar</name>
  <config-items/>
</Foobar>
muffi-dn commented 8 months ago

thanks @dapper91 will give it a go.