Compound FieldsΒΆ

For repeating choice elements or complicated sequence elements you can use compound fields in order to preserve the elements ordering during roundtrip conversions.

$ xsdata tests/fixtures/compound/schema.xsd --compound-fields --package tests.fixtures.compound.models --structure-style single-package
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="root">
    <xsd:complexType>
      <xsd:choice maxOccurs="unbounded">
        <xsd:element ref="alpha" />
        <xsd:element ref="bravo" />
      </xsd:choice>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="alpha">
    <xsd:complexType>
      <xsd:attribute name="a" type="xsd:boolean" fixed="true" />
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="bravo">
    <xsd:complexType>
      <xsd:attribute name="b" type="xsd:boolean" fixed="true" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>
@dataclass
class Root:
    class Meta:
        name = "root"

    alpha_or_bravo: List[object] = field(
        default_factory=list,
        metadata={
            "type": "Elements",
            "choices": (
                {
                    "name": "alpha",
                    "type": Alpha,
                },
                {
                    "name": "bravo",
                    "type": Bravo,
                },
            ),
        }
    )

All choice elements are grouped into a single list field.

from pathlib import Path
from tests.fixtures.compound.models import Root
from tests import fixtures_dir
from xsdata.formats.dataclass.parsers import XmlParser

xml_path = fixtures_dir.joinpath("compound/sample.xml")
parser = XmlParser()
root = parser.from_path(xml_path, Root)
print(root.alpha_or_bravo)
[Alpha(a=True), Alpha(a=True), Bravo(b=True), Bravo(b=True), Alpha(a=True), Bravo(b=True), Alpha(a=True), Bravo(b=True)]