xsdata icon indicating copy to clipboard operation
xsdata copied to clipboard

Wrapper fails if collection items element name is reused

Open lovette opened this issue 7 months ago • 0 comments

I'm trying to parse XML that contains two collections (Foos and Bars) that both use the same element name for collection items (Property). Is it possible to achieve this using "wrapper"? The following fails with TypeError: Foo.__init__() missing 1 required positional argument: 'foo_id'.

from dataclasses import dataclass, field

from xsdata.formats.dataclass.parsers import XmlParser


@dataclass
class Foo:
    class Meta:
        name = "Property"

    foo_id: int = field(
        metadata={
            "name": "Foo-Id",
            "type": "Attribute",
        },
    )


@dataclass
class Bar:
    class Meta:
        name = "Property"

    bar_id: str = field(
        metadata={
            "name": "Bar-Id",
            "type": "Attribute",
        },
    )


@dataclass
class Response:
    foos: list[Foo] = field(
        metadata={
            "wrapper": "Foos",
            "name": "Property",
            "type": "Element",
            "required": True,
            "min_occurs": 1,
        }
    )
    bars: list[Bar] = field(
        metadata={
            "wrapper": "Bars",
            "name": "Property",
            "type": "Element",
            "required": True,
            "min_occurs": 1,
        }
    )


xml = """
<Response>
    <Foos>
        <Property Foo-Id="1" />
        <Property Foo-Id="2" />
    </Foos>
    <Bars>
        <Property Bar-Id="3" />
        <Property Bar-Id="4" />
    </Bars>
</Response>
"""

parser = XmlParser()
p = parser.from_string(xml, Response)

print(p.foos)
print(p.bars)

lovette avatar May 12 '25 01:05 lovette