diff --git a/tests/formats/dataclass/serializers/tree/test_mixins.py b/tests/formats/dataclass/serializers/tree/test_mixins.py index eab86c502..f01b80b57 100644 --- a/tests/formats/dataclass/serializers/tree/test_mixins.py +++ b/tests/formats/dataclass/serializers/tree/test_mixins.py @@ -19,3 +19,9 @@ def test_build_with_unknown_event(self, mock_generate): serializer.build(books, builder) self.assertEqual("Unhandled event: `foobar`.", str(cm.exception)) + + def test_encode_data(self): + self.assertEqual("", TreeSerializer.encode_data(None)) + self.assertEqual("", TreeSerializer.encode_data([])) + self.assertEqual("", TreeSerializer.encode_data("")) + self.assertEqual("1 2 3", TreeSerializer.encode_data([1, 2, 3])) diff --git a/xsdata/formats/dataclass/serializers/tree/mixins.py b/xsdata/formats/dataclass/serializers/tree/mixins.py index d1fa703c6..488ba7177 100644 --- a/xsdata/formats/dataclass/serializers/tree/mixins.py +++ b/xsdata/formats/dataclass/serializers/tree/mixins.py @@ -1,8 +1,9 @@ import abc from dataclasses import dataclass -from typing import Any, Dict, Protocol +from typing import Any, Dict, Optional, Protocol from xsdata.exceptions import XmlHandlerError +from xsdata.formats.converter import converter from xsdata.formats.dataclass.serializers.mixins import EventGenerator, XmlWriterEvent from xsdata.formats.types import T from xsdata.models.enums import EventType @@ -50,10 +51,28 @@ def build(self, obj: T, builder: TreeBuilder): elif event == XmlWriterEvent.ATTR: key, value = element pending_attrs[key] = value - elif event == EventType.END: builder.end(*element) elif event == XmlWriterEvent.DATA: - builder.data(*element) + data = self.encode_data(element[0]) + builder.data(data) else: raise XmlHandlerError(f"Unhandled event: `{event}`.") + + @classmethod + def encode_data(cls, data: Any) -> str: + """Encode data for xml rendering. + + Args: + data: The content to encode/serialize + + Returns: + The xml encoded data + """ + if data is None or isinstance(data, list) and not data: + return "" + + if isinstance(data, str): + return data + + return converter.serialize(data)