Skip to content

Commit bd36869

Browse files
committed
Change HomogeneousSerializerFactory to support inline lists
This makes it possible to support the xsd:list tag in xml schema.
1 parent b4d75c7 commit bd36869

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

pydantic_xml/serializers.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,23 @@ class HomogeneousSerializerFactory:
558558
Homogeneous collection type serializer factory.
559559
"""
560560

561+
class TextSerializer(Serializer):
562+
def serialize(
563+
self, element: etree.Element, value: Any, *, encoder: XmlEncoder, skip_empty: bool = False,
564+
) -> Optional[etree.Element]:
565+
if value is None or skip_empty and len(value) == 0:
566+
return element
567+
568+
encoded = " ".join(encoder.encode(val) for val in value)
569+
element.text = encoded
570+
return element
571+
572+
def deserialize(self, element: etree.Element) -> Optional[List[Any]]:
573+
return [
574+
value
575+
for value in element.text.split()
576+
]
577+
561578
class ElementSerializer(Serializer):
562579
def __init__(
563580
self, model: Type['pxml.BaseXmlModel'], model_field: pd.fields.ModelField, ctx: Serializer.Context,
@@ -633,7 +650,7 @@ def build(
633650
if field_location is Location.ELEMENT:
634651
return cls.ElementSerializer(model, model_field, ctx)
635652
elif field_location is Location.MISSING:
636-
return cls.ElementSerializer(model, model_field, ctx)
653+
return cls.TextSerializer()
637654
elif field_location is Location.ATTRIBUTE:
638655
raise errors.ModelFieldError(
639656
model.__name__, model_field.name, "attributes of collection type are not supported",

tests/test_homogeneous_collections.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,25 @@ class RootModel(BaseXmlModel, tag='model'):
121121
assert_xml_equal(actual_xml, xml)
122122

123123

124+
def test_text_list_extraction():
125+
class RootModel(BaseXmlModel, tag="model"):
126+
values: List[int]
127+
128+
xml = '''
129+
<model>1 2 70 -34</model>
130+
'''
131+
132+
actual_obj = RootModel.from_xml(xml)
133+
expected_obj = RootModel(
134+
values = [1, 2, 70, -34]
135+
)
136+
137+
assert actual_obj == expected_obj
138+
139+
actual_xml = actual_obj.to_xml()
140+
assert_xml_equal(actual_xml, xml)
141+
142+
124143
def test_homogeneous_definition_errors():
125144
with pytest.raises(errors.ModelFieldError):
126145
class TestModel(BaseXmlModel):

0 commit comments

Comments
 (0)