Skip to content

Commit

Permalink
fix: Encode data in tree serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
tefra committed Apr 23, 2024
1 parent df871c8 commit 1030149
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
6 changes: 6 additions & 0 deletions tests/formats/dataclass/serializers/tree/test_mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]))
25 changes: 22 additions & 3 deletions xsdata/formats/dataclass/serializers/tree/mixins.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)

0 comments on commit 1030149

Please sign in to comment.