Skip to content

elements

xsdata.formats.dataclass.models.elements

XmlType

Xml node types.

Source code in xsdata/formats/dataclass/models/elements.py
26
27
28
29
30
31
32
33
34
35
class XmlType:
    """Xml node types."""

    TEXT = sys.intern("Text")
    ELEMENT = sys.intern("Element")
    ELEMENTS = sys.intern("Elements")
    WILDCARD = sys.intern("Wildcard")
    ATTRIBUTE = sys.intern("Attribute")
    ATTRIBUTES = sys.intern("Attributes")
    IGNORE = sys.intern("Ignore")

MetaMixin

Use this mixin for unit tests only!!!

Source code in xsdata/formats/dataclass/models/elements.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class MetaMixin:
    """Use this mixin for unit tests only!!!"""

    __slots__: Tuple[str, ...] = ()

    def __eq__(self, other: Any) -> bool:
        """Implement equality operator."""
        return tuple(self) == tuple(other)

    def __iter__(self) -> Iterator:
        """Implement iteration."""
        for name in self.__slots__:
            yield getattr(self, name)

    def __repr__(self) -> str:
        """Implement representation."""
        params = (f"{name}={getattr(self, name)!r}" for name in self.__slots__)
        return f"{self.__class__.__qualname__}({', '.join(params)})"

__eq__(other)

Implement equality operator.

Source code in xsdata/formats/dataclass/models/elements.py
43
44
45
def __eq__(self, other: Any) -> bool:
    """Implement equality operator."""
    return tuple(self) == tuple(other)

__iter__()

Implement iteration.

Source code in xsdata/formats/dataclass/models/elements.py
47
48
49
50
def __iter__(self) -> Iterator:
    """Implement iteration."""
    for name in self.__slots__:
        yield getattr(self, name)

__repr__()

Implement representation.

Source code in xsdata/formats/dataclass/models/elements.py
52
53
54
55
def __repr__(self) -> str:
    """Implement representation."""
    params = (f"{name}={getattr(self, name)!r}" for name in self.__slots__)
    return f"{self.__class__.__qualname__}({', '.join(params)})"

XmlVar

Bases: MetaMixin

Class field binding metadata.

Parameters:

Name Type Description Default
index int

Position index of the variable

required
name str

Name of the variable

required
local_name str

Local name of the variable

required
wrapper Optional[str]

The element wrapper name

required
types Sequence[Type]

Supported types for the variable

required
clazz Optional[Type]

Target class type

required
init bool

Indicates if the field should be included in the constructor

required
mixed bool

Indicates if the field supports mixed content type values.

required
factory Optional[Callable]

Callable factory for lists

required
tokens_factory Optional[Callable]

Callable factory for tokens

required
format Optional[str]

Information about the value format

required
any_type bool

Indicates if the field supports dynamic value types

required
process_contents str

Information about processing contents

required
required bool

Indicates if the field is mandatory

required
nillable bool

Indicates if the field supports nillable content

required
sequence Optional[int]

Specifies rendering values in sequential mode

required
default Any

Default value or factory for the field

required
xml_type str

Type of the XML field (element, attribute, etc.)

required
namespaces Sequence[str]

List of supported namespaces

required
elements Mapping[str, XmlVar]

Mapping of qualified name-repeatable elements

required
wildcards Sequence[XmlVar]

List of repeatable wildcards

required

Attributes:

Name Type Description
qname

Namespace-qualified name of the variable

wrapper_qname

Namespace-qualified name of the variable wrapper

tokens

Indicates if the field has associated tokens

list_element

Indicates if the field is a list or tuple element

namespace_matches Optional[Dict[str, bool]]

Matching namespaces information

is_clazz_union

Indicates if the field is a union of multiple types

is_text

Indicates if the field represents text content

is_element

Indicates if the field represents an XML element

is_elements

Indicates if the field represents a sequence of XML elements

is_wildcard

Indicates if the field represents a wildcard

is_attribute

Indicates if the field represents an XML attribute

is_attributes

Indicates if the field represents a sequence of XML attributes

Source code in xsdata/formats/dataclass/models/elements.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
class XmlVar(MetaMixin):
    """Class field binding metadata.

    Args:
        index: Position index of the variable
        name: Name of the variable
        local_name: Local name of the variable
        wrapper: The element wrapper name
        types: Supported types for the variable
        clazz: Target class type
        init: Indicates if the field should be included in the constructor
        mixed: Indicates if the field supports mixed content type values.
        factory: Callable factory for lists
        tokens_factory: Callable factory for tokens
        format: Information about the value format
        any_type: Indicates if the field supports dynamic value types
        process_contents: Information about processing contents
        required: Indicates if the field is mandatory
        nillable: Indicates if the field supports nillable content
        sequence: Specifies rendering values in sequential mode
        default: Default value or factory for the field
        xml_type: Type of the XML field (element, attribute, etc.)
        namespaces: List of supported namespaces
        elements: Mapping of qualified name-repeatable elements
        wildcards: List of repeatable wildcards

    Attributes:
        qname: Namespace-qualified name of the variable
        wrapper_qname: Namespace-qualified name of the variable wrapper
        tokens: Indicates if the field has associated tokens
        list_element: Indicates if the field is a list or tuple element
        namespace_matches: Matching namespaces information
        is_clazz_union: Indicates if the field is a union of multiple types
        is_text: Indicates if the field represents text content
        is_element: Indicates if the field represents an XML element
        is_elements: Indicates if the field represents a sequence of XML elements
        is_wildcard: Indicates if the field represents a wildcard
        is_attribute: Indicates if the field represents an XML attribute
        is_attributes: Indicates if the field represents a sequence of XML attributes
    """

    __slots__ = (
        "index",
        "name",
        "local_name",
        "wrapper",
        "types",
        "clazz",
        "init",
        "mixed",
        "factory",
        "tokens_factory",
        "format",
        "any_type",
        "process_contents",
        "required",
        "nillable",
        "sequence",
        "default",
        "namespaces",
        "elements",
        "wildcards",
        # Calculated
        "qname",
        "wrapper_qname",
        "tokens",
        "list_element",
        "is_text",
        "is_element",
        "is_elements",
        "is_wildcard",
        "is_attribute",
        "is_attributes",
        "namespace_matches",
        "is_clazz_union",
    )

    def __init__(
        self,
        index: int,
        name: str,
        local_name: str,
        wrapper: Optional[str],
        types: Sequence[Type],
        clazz: Optional[Type],
        init: bool,
        mixed: bool,
        factory: Optional[Callable],
        tokens_factory: Optional[Callable],
        format: Optional[str],
        any_type: bool,
        process_contents: str,
        required: bool,
        nillable: bool,
        sequence: Optional[int],
        default: Any,
        xml_type: str,
        namespaces: Sequence[str],
        elements: Mapping[str, "XmlVar"],
        wildcards: Sequence["XmlVar"],
        **kwargs: Any,
    ):
        self.index = index
        self.name = name
        self.local_name = local_name
        self.wrapper = wrapper
        self.types = types
        self.clazz = clazz
        self.init = init
        self.mixed = mixed
        self.tokens = tokens_factory is not None
        self.format = format
        self.any_type = any_type
        self.process_contents = process_contents
        self.required = required
        self.nillable = nillable
        self.sequence = sequence
        self.list_element = factory in (list, tuple)
        self.default = default
        self.namespaces = namespaces
        self.elements = elements
        self.wildcards = wildcards
        self.wrapper = wrapper
        self.factory = factory
        self.tokens_factory = tokens_factory

        self.namespace_matches: Optional[Dict[str, bool]] = None
        self.is_clazz_union = self.clazz and len(types) > 1

        namespace = default_namespace(namespaces)

        self.qname = build_qname(namespace, local_name)
        self.wrapper_qname = None
        if wrapper:
            self.wrapper_qname = build_qname(namespace, wrapper)

        self.is_text = False
        self.is_element = False
        self.is_elements = False
        self.is_wildcard = False
        self.is_attribute = False
        self.is_attributes = False

        if xml_type == XmlType.ELEMENTS:
            self.is_elements = True
        elif xml_type == XmlType.ELEMENT or self.clazz:
            self.is_element = True
        elif xml_type == XmlType.ATTRIBUTE:
            self.is_attribute = True
        elif xml_type == XmlType.ATTRIBUTES:
            self.is_attributes = True
        elif xml_type == XmlType.WILDCARD:
            self.is_wildcard = True
        else:
            self.is_text = True

    @property
    def element_types(self) -> Set[Type]:
        """Return the unique element types."""
        return {tp for element in self.elements.values() for tp in element.types}

    def find_choice(self, qname: str) -> Optional["XmlVar"]:
        """Match and return a choice field by its qualified name.

        Args:
            qname: The qualified name to lookup

        Returns:
            The choice xml var instance or None if there are no matches.
        """
        match = self.elements.get(qname)
        return match or find_by_namespace(self.wildcards, qname)

    def find_value_choice(self, value: Any, is_class: bool) -> Optional["XmlVar"]:
        """Match and return a choice field that matches the given value.

        Cases:
            - value is none or empty tokens list: look for a nillable choice
            - value is a dataclass: look for exact type or a subclass
            - value is primitive: test value against the converter

        Args:
            value: The value to match its type to one of the choices
            is_class: Whether the value is a binding class

        Returns:
            The choice xml var instance or None if there are no matches.
        """
        is_tokens = collections.is_array(value)
        if value is None or (not value and is_tokens):
            return self.find_nillable_choice(is_tokens)

        if is_class:
            return self.find_clazz_choice(type(value))

        return self.find_primitive_choice(value, is_tokens)

    def find_nillable_choice(self, is_tokens: bool) -> Optional["XmlVar"]:
        """Find the first nillable choice.

        Args:
            is_tokens: Specify if the choice must support token values

        Returns:
            The choice xml var instance or None if there are no matches.
        """
        return collections.first(
            element
            for element in self.elements.values()
            if element.nillable and is_tokens == element.tokens
        )

    def find_clazz_choice(self, clazz: Type) -> Optional["XmlVar"]:
        """Find the best matching choice for the given class.

        Best Matches:
            1. The class is explicitly defined in a choice types
            2. The class is a subclass of one of the choice types

        Args:
            clazz: The class type to match

        Returns:
            The choice xml var instance or None if there are no matches.
        """
        derived = None
        for element in self.elements.values():
            if not element.clazz:
                continue

            if clazz in element.types:
                return element

            if derived is None and any(issubclass(clazz, t) for t in element.types):
                derived = element

        return derived

    def find_primitive_choice(self, value: Any, is_tokens: bool) -> Optional["XmlVar"]:
        """Match and return a choice field that matches the given primitive value.

        Args:
            value: A primitive value, e.g. str, int, float, enum
            is_tokens: Specify whether it's a tokens value

        Returns:
            The choice xml var instance or None if there are no matches.
        """
        tp = type(value) if not is_tokens else type(value[0])
        for element in self.elements.values():
            if (element.any_type or element.clazz) or element.tokens != is_tokens:
                continue

            if tp in element.types:
                return element

            if is_tokens and all(converter.test(val, element.types) for val in value):
                return element

            if converter.test(value, element.types):
                return element

        return None

    def is_optional(self, value: Any) -> bool:
        """Verify this var is optional and the value matches the default one.

        Args:
            value: The value to compare against the default one

        Returns:
            The bool result.
        """
        if self.required:
            return False

        if callable(self.default):
            return self.default() == value
        return self.default == value

    def match_namespace(self, qname: str) -> bool:
        """Match the given qname to the wildcard allowed namespaces.

        Args:
            qname: The namespace qualified name of an element

        Returns:
            The bool result.
        """
        if self.namespace_matches is None:
            self.namespace_matches = {}

        matches = self.namespace_matches.get(qname)
        if matches is None:
            matches = self._match_namespace(qname)
            self.namespace_matches[qname] = matches

        return matches

    def _match_namespace(self, qname: str) -> bool:
        uri = target_uri(qname)
        if not self.namespaces and uri is None:
            return True

        for check in self.namespaces:
            if (
                (not check and uri is None)
                or check == uri
                or check == NamespaceType.ANY_NS
                or (check and check[0] == "!" and check[1:] != uri)
            ):
                return True

        return False

element_types: Set[Type] property

Return the unique element types.

find_choice(qname)

Match and return a choice field by its qualified name.

Parameters:

Name Type Description Default
qname str

The qualified name to lookup

required

Returns:

Type Description
Optional[XmlVar]

The choice xml var instance or None if there are no matches.

Source code in xsdata/formats/dataclass/models/elements.py
237
238
239
240
241
242
243
244
245
246
247
def find_choice(self, qname: str) -> Optional["XmlVar"]:
    """Match and return a choice field by its qualified name.

    Args:
        qname: The qualified name to lookup

    Returns:
        The choice xml var instance or None if there are no matches.
    """
    match = self.elements.get(qname)
    return match or find_by_namespace(self.wildcards, qname)

find_value_choice(value, is_class)

Match and return a choice field that matches the given value.

Cases
  • value is none or empty tokens list: look for a nillable choice
  • value is a dataclass: look for exact type or a subclass
  • value is primitive: test value against the converter

Parameters:

Name Type Description Default
value Any

The value to match its type to one of the choices

required
is_class bool

Whether the value is a binding class

required

Returns:

Type Description
Optional[XmlVar]

The choice xml var instance or None if there are no matches.

Source code in xsdata/formats/dataclass/models/elements.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def find_value_choice(self, value: Any, is_class: bool) -> Optional["XmlVar"]:
    """Match and return a choice field that matches the given value.

    Cases:
        - value is none or empty tokens list: look for a nillable choice
        - value is a dataclass: look for exact type or a subclass
        - value is primitive: test value against the converter

    Args:
        value: The value to match its type to one of the choices
        is_class: Whether the value is a binding class

    Returns:
        The choice xml var instance or None if there are no matches.
    """
    is_tokens = collections.is_array(value)
    if value is None or (not value and is_tokens):
        return self.find_nillable_choice(is_tokens)

    if is_class:
        return self.find_clazz_choice(type(value))

    return self.find_primitive_choice(value, is_tokens)

find_nillable_choice(is_tokens)

Find the first nillable choice.

Parameters:

Name Type Description Default
is_tokens bool

Specify if the choice must support token values

required

Returns:

Type Description
Optional[XmlVar]

The choice xml var instance or None if there are no matches.

Source code in xsdata/formats/dataclass/models/elements.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def find_nillable_choice(self, is_tokens: bool) -> Optional["XmlVar"]:
    """Find the first nillable choice.

    Args:
        is_tokens: Specify if the choice must support token values

    Returns:
        The choice xml var instance or None if there are no matches.
    """
    return collections.first(
        element
        for element in self.elements.values()
        if element.nillable and is_tokens == element.tokens
    )

find_clazz_choice(clazz)

Find the best matching choice for the given class.

Best Matches
  1. The class is explicitly defined in a choice types
  2. The class is a subclass of one of the choice types

Parameters:

Name Type Description Default
clazz Type

The class type to match

required

Returns:

Type Description
Optional[XmlVar]

The choice xml var instance or None if there are no matches.

Source code in xsdata/formats/dataclass/models/elements.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def find_clazz_choice(self, clazz: Type) -> Optional["XmlVar"]:
    """Find the best matching choice for the given class.

    Best Matches:
        1. The class is explicitly defined in a choice types
        2. The class is a subclass of one of the choice types

    Args:
        clazz: The class type to match

    Returns:
        The choice xml var instance or None if there are no matches.
    """
    derived = None
    for element in self.elements.values():
        if not element.clazz:
            continue

        if clazz in element.types:
            return element

        if derived is None and any(issubclass(clazz, t) for t in element.types):
            derived = element

    return derived

find_primitive_choice(value, is_tokens)

Match and return a choice field that matches the given primitive value.

Parameters:

Name Type Description Default
value Any

A primitive value, e.g. str, int, float, enum

required
is_tokens bool

Specify whether it's a tokens value

required

Returns:

Type Description
Optional[XmlVar]

The choice xml var instance or None if there are no matches.

Source code in xsdata/formats/dataclass/models/elements.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def find_primitive_choice(self, value: Any, is_tokens: bool) -> Optional["XmlVar"]:
    """Match and return a choice field that matches the given primitive value.

    Args:
        value: A primitive value, e.g. str, int, float, enum
        is_tokens: Specify whether it's a tokens value

    Returns:
        The choice xml var instance or None if there are no matches.
    """
    tp = type(value) if not is_tokens else type(value[0])
    for element in self.elements.values():
        if (element.any_type or element.clazz) or element.tokens != is_tokens:
            continue

        if tp in element.types:
            return element

        if is_tokens and all(converter.test(val, element.types) for val in value):
            return element

        if converter.test(value, element.types):
            return element

    return None

is_optional(value)

Verify this var is optional and the value matches the default one.

Parameters:

Name Type Description Default
value Any

The value to compare against the default one

required

Returns:

Type Description
bool

The bool result.

Source code in xsdata/formats/dataclass/models/elements.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def is_optional(self, value: Any) -> bool:
    """Verify this var is optional and the value matches the default one.

    Args:
        value: The value to compare against the default one

    Returns:
        The bool result.
    """
    if self.required:
        return False

    if callable(self.default):
        return self.default() == value
    return self.default == value

match_namespace(qname)

Match the given qname to the wildcard allowed namespaces.

Parameters:

Name Type Description Default
qname str

The namespace qualified name of an element

required

Returns:

Type Description
bool

The bool result.

Source code in xsdata/formats/dataclass/models/elements.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def match_namespace(self, qname: str) -> bool:
    """Match the given qname to the wildcard allowed namespaces.

    Args:
        qname: The namespace qualified name of an element

    Returns:
        The bool result.
    """
    if self.namespace_matches is None:
        self.namespace_matches = {}

    matches = self.namespace_matches.get(qname)
    if matches is None:
        matches = self._match_namespace(qname)
        self.namespace_matches[qname] = matches

    return matches

XmlMeta

Bases: MetaMixin

Class binding metadata.

Parameters:

Name Type Description Default
clazz Type

The binding model

required
qname str

The namespace-qualified name

required
target_qname Optional[str]

The target namespace-qualified name

required
nillable bool

Specifies whether this class supports nillable content

required
text Optional[XmlVar]

A text variable

required
choices Sequence[XmlVar]

A list of compound variables

required
elements Mapping[str, Sequence[XmlVar]]

A mapping of qualified name to sequence of element variables

required
wildcards Sequence[XmlVar]

A list of wildcard variables

required
attributes Mapping[str, XmlVar]

A mapping of qualified name to attribute variable

required
any_attributes Sequence[XmlVar]

A list of wildcard variables

required
wrappers Mapping[str, str]

a mapping of wrapper names to sequences of wrapped variables

required

Attributes:

Name Type Description
namespace

The target namespace extracted from the qualified name

mixed_content

Specifies if the class supports mixed content

Source code in xsdata/formats/dataclass/models/elements.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
class XmlMeta(MetaMixin):
    """Class binding metadata.

    Args:
        clazz: The binding model
        qname: The namespace-qualified name
        target_qname: The target namespace-qualified name
        nillable: Specifies whether this class supports nillable content
        text: A text variable
        choices: A list of compound variables
        elements: A mapping of qualified name to sequence of element variables
        wildcards: A list of wildcard variables
        attributes: A mapping of qualified name to attribute variable
        any_attributes: A list of wildcard variables
        wrappers: a mapping of wrapper names to sequences of wrapped variables

    Attributes:
        namespace: The target namespace extracted from the qualified name
        mixed_content: Specifies if the class supports mixed content
    """

    __slots__ = (
        "clazz",
        "qname",
        "target_qname",
        "nillable",
        "text",
        "choices",
        "elements",
        "wildcards",
        "attributes",
        "any_attributes",
        "wrappers",
        # Calculated
        "namespace",
        "mixed_content",
    )

    def __init__(
        self,
        clazz: Type,
        qname: str,
        target_qname: Optional[str],
        nillable: bool,
        text: Optional[XmlVar],
        choices: Sequence[XmlVar],
        elements: Mapping[str, Sequence[XmlVar]],
        wildcards: Sequence[XmlVar],
        attributes: Mapping[str, XmlVar],
        any_attributes: Sequence[XmlVar],
        wrappers: Mapping[str, str],
        **kwargs: Any,
    ):
        self.clazz = clazz
        self.qname = qname
        self.namespace = target_uri(qname)
        self.target_qname = target_qname
        self.nillable = nillable
        self.text = text
        self.choices = choices
        self.elements = elements
        self.wildcards = wildcards
        self.attributes = attributes
        self.any_attributes = any_attributes
        self.mixed_content = any(wildcard.mixed for wildcard in self.wildcards)
        self.wrappers = wrappers

    @property
    def element_types(self) -> Set[Type]:
        """Return a unique list of all elements types."""
        return {
            tp
            for elements in self.elements.values()
            for element in elements
            for tp in element.types
        }

    def get_element_vars(self) -> List[XmlVar]:
        """Return a sorted list of the class element variables."""
        result = list(
            itertools.chain(self.wildcards, self.choices, *self.elements.values())
        )
        if self.text:
            result.append(self.text)

        return sorted(result, key=get_index)

    def get_attribute_vars(self) -> List[XmlVar]:
        """Return a sorted list of the class attribute variables."""
        result = itertools.chain(self.any_attributes, self.attributes.values())
        return sorted(result, key=get_index)

    def get_all_vars(self) -> List[XmlVar]:
        """Return a sorted list of all the class variables."""
        result = list(
            itertools.chain(
                self.wildcards,
                self.choices,
                self.any_attributes,
                self.attributes.values(),
                *self.elements.values(),
            )
        )
        if self.text:
            result.append(self.text)

        return sorted(result, key=get_index)

    def find_attribute(self, qname: str) -> Optional[XmlVar]:
        """Find an attribute var with the given qname.

        Args:
            qname: The namespace qualified name

        Returns:
            The xml var instance or None if there is no match.
        """
        return self.attributes.get(qname)

    def find_any_attributes(self, qname: str) -> Optional[XmlVar]:
        """Find a wildcard attribute var that matches the given qname.

        Args:
            qname: The namespace qualified name

        Returns:
            The xml var instance or None if there is no match.
        """
        return find_by_namespace(self.any_attributes, qname)

    def find_wildcard(self, qname: str) -> Optional[XmlVar]:
        """Find a wildcard var that matches the given qname.

        If the wildcard has choices, attempt to match and return
        one of them as well.

        Args:
            qname: The namespace qualified name

        Returns:
            The xml var instance or None if there is no match.
        """
        wildcard = find_by_namespace(self.wildcards, qname)

        if wildcard and wildcard.elements:
            choice = wildcard.find_choice(qname)
            if choice:
                return choice

        return wildcard

    def find_any_wildcard(self) -> Optional[XmlVar]:
        """Return the first declared wildcard var.

        Returns:
            The xml var instance or None if there are no wildcard vars.
        """
        return self.wildcards[0] if self.wildcards else None

    def find_children(self, qname: str) -> Iterator[XmlVar]:
        """Find all class vars that match the given qname.

        Go through the elements, choices and wildcards. Sometimes
        a class might contain more than one var with the same
        qualified name. The binding process has to check all
        of them and see which one to use.

        Args:
            qname: The namespace qualified name

        Yields:
            An iterator of all the class vars that match the given qname.
        """
        elements = self.elements.get(qname)
        if elements:
            yield from elements

        for choice in self.choices:
            match = choice.find_choice(qname)
            if match:
                yield match

        chd = self.find_wildcard(qname)
        if chd:
            yield chd

element_types: Set[Type] property

Return a unique list of all elements types.

get_element_vars()

Return a sorted list of the class element variables.

Source code in xsdata/formats/dataclass/models/elements.py
472
473
474
475
476
477
478
479
480
def get_element_vars(self) -> List[XmlVar]:
    """Return a sorted list of the class element variables."""
    result = list(
        itertools.chain(self.wildcards, self.choices, *self.elements.values())
    )
    if self.text:
        result.append(self.text)

    return sorted(result, key=get_index)

get_attribute_vars()

Return a sorted list of the class attribute variables.

Source code in xsdata/formats/dataclass/models/elements.py
482
483
484
485
def get_attribute_vars(self) -> List[XmlVar]:
    """Return a sorted list of the class attribute variables."""
    result = itertools.chain(self.any_attributes, self.attributes.values())
    return sorted(result, key=get_index)

get_all_vars()

Return a sorted list of all the class variables.

Source code in xsdata/formats/dataclass/models/elements.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def get_all_vars(self) -> List[XmlVar]:
    """Return a sorted list of all the class variables."""
    result = list(
        itertools.chain(
            self.wildcards,
            self.choices,
            self.any_attributes,
            self.attributes.values(),
            *self.elements.values(),
        )
    )
    if self.text:
        result.append(self.text)

    return sorted(result, key=get_index)

find_attribute(qname)

Find an attribute var with the given qname.

Parameters:

Name Type Description Default
qname str

The namespace qualified name

required

Returns:

Type Description
Optional[XmlVar]

The xml var instance or None if there is no match.

Source code in xsdata/formats/dataclass/models/elements.py
503
504
505
506
507
508
509
510
511
512
def find_attribute(self, qname: str) -> Optional[XmlVar]:
    """Find an attribute var with the given qname.

    Args:
        qname: The namespace qualified name

    Returns:
        The xml var instance or None if there is no match.
    """
    return self.attributes.get(qname)

find_any_attributes(qname)

Find a wildcard attribute var that matches the given qname.

Parameters:

Name Type Description Default
qname str

The namespace qualified name

required

Returns:

Type Description
Optional[XmlVar]

The xml var instance or None if there is no match.

Source code in xsdata/formats/dataclass/models/elements.py
514
515
516
517
518
519
520
521
522
523
def find_any_attributes(self, qname: str) -> Optional[XmlVar]:
    """Find a wildcard attribute var that matches the given qname.

    Args:
        qname: The namespace qualified name

    Returns:
        The xml var instance or None if there is no match.
    """
    return find_by_namespace(self.any_attributes, qname)

find_wildcard(qname)

Find a wildcard var that matches the given qname.

If the wildcard has choices, attempt to match and return one of them as well.

Parameters:

Name Type Description Default
qname str

The namespace qualified name

required

Returns:

Type Description
Optional[XmlVar]

The xml var instance or None if there is no match.

Source code in xsdata/formats/dataclass/models/elements.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def find_wildcard(self, qname: str) -> Optional[XmlVar]:
    """Find a wildcard var that matches the given qname.

    If the wildcard has choices, attempt to match and return
    one of them as well.

    Args:
        qname: The namespace qualified name

    Returns:
        The xml var instance or None if there is no match.
    """
    wildcard = find_by_namespace(self.wildcards, qname)

    if wildcard and wildcard.elements:
        choice = wildcard.find_choice(qname)
        if choice:
            return choice

    return wildcard

find_any_wildcard()

Return the first declared wildcard var.

Returns:

Type Description
Optional[XmlVar]

The xml var instance or None if there are no wildcard vars.

Source code in xsdata/formats/dataclass/models/elements.py
546
547
548
549
550
551
552
def find_any_wildcard(self) -> Optional[XmlVar]:
    """Return the first declared wildcard var.

    Returns:
        The xml var instance or None if there are no wildcard vars.
    """
    return self.wildcards[0] if self.wildcards else None

find_children(qname)

Find all class vars that match the given qname.

Go through the elements, choices and wildcards. Sometimes a class might contain more than one var with the same qualified name. The binding process has to check all of them and see which one to use.

Parameters:

Name Type Description Default
qname str

The namespace qualified name

required

Yields:

Type Description
XmlVar

An iterator of all the class vars that match the given qname.

Source code in xsdata/formats/dataclass/models/elements.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
def find_children(self, qname: str) -> Iterator[XmlVar]:
    """Find all class vars that match the given qname.

    Go through the elements, choices and wildcards. Sometimes
    a class might contain more than one var with the same
    qualified name. The binding process has to check all
    of them and see which one to use.

    Args:
        qname: The namespace qualified name

    Yields:
        An iterator of all the class vars that match the given qname.
    """
    elements = self.elements.get(qname)
    if elements:
        yield from elements

    for choice in self.choices:
        match = choice.find_choice(qname)
        if match:
            yield match

    chd = self.find_wildcard(qname)
    if chd:
        yield chd

default_namespace(namespaces)

Return the first valid namespace uri or None.

Parameters:

Name Type Description Default
namespaces Sequence[str]

A list of namespace options which may include valid uri(s) or a placeholder e.g. ##any, ##other,

targetNamespace, ##local
required

Returns:

Type Description
Optional[str]

A namespace uri or None if there isn't any.

Source code in xsdata/formats/dataclass/models/elements.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def default_namespace(namespaces: Sequence[str]) -> Optional[str]:
    """Return the first valid namespace uri or None.

    Args:
        namespaces: A list of namespace options which may include
            valid uri(s) or a placeholder e.g. ##any, ##other,
            ##targetNamespace, ##local

    Returns:
        A namespace uri or None if there isn't any.
    """
    for namespace in namespaces:
        if namespace and not namespace.startswith("#"):
            return namespace

    return None

find_by_namespace(vars, qname)

Match the given qname to one of the given vars.

Parameters:

Name Type Description Default
vars Sequence[XmlVar]

The list of vars to match

required
qname str

The namespace qualified name to lookup

required

Returns:

Type Description
Optional[XmlVar]

The first matching xml var instance or None if there are no matches.

Source code in xsdata/formats/dataclass/models/elements.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
def find_by_namespace(vars: Sequence[XmlVar], qname: str) -> Optional[XmlVar]:
    """Match the given qname to one of the given vars.

    Args:
        vars: The list of vars to match
        qname: The namespace qualified name to lookup

    Returns:
        The first matching xml var instance or None if there are no matches.
    """
    for xml_var in vars:
        if xml_var.match_namespace(qname):
            return xml_var

    return None