dapper91 / pydantic-xml

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

skip_empty produces invalid xml #194

Open spacemanspiff2007 opened 1 month ago

spacemanspiff2007 commented 1 month ago

I have the following schema (from a bigger xml) which defines a node as mandatory: grafik

However since there are many optional values in the xml I'd like to serialize without the default values (which are None in my case). That's why I call to_xml with skip_empty set to True. Unfortunately this also removes the required node thus producing an invalid xml.

from pydantic_xml import BaseXmlModel, attr, element

class Codes(BaseXmlModel, tag='codes'):
    codes: list[str] = element(tag='code')

class MyData(BaseXmlModel, tag='MyData'):
    revision: str = attr()
    codes: Codes

d = MyData(revision='MyData 1', codes=Codes(codes=[]))

for line in d.to_xml(pretty_print=True, encoding='utf-8', skip_empty=True).decode().splitlines():
    print(line)

produces

<MyData revision="MyData 1"/>

As you can see codes is not optional but gets wrongly removed.

I would like to have

<MyData revision="MyData 1">
    <codes />
</MyData>

Would it be possible to add another parameter skip_none or skip_unset like in pydantic which would work accordingly?

dapper91 commented 4 days ago

@spacemanspiff2007 Hi,

Right now there is not way to skip None's only. I will try to add this feature in future releases.