Skip to content

Package API

Functions and supporting models. Every class and function defined in these modules is listed, generated from the code.

Loading, saving and validation

load_model(filepath, use_cache=True)

Source code in dsbxml\utils.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def load_model(filepath: str | Path, use_cache: bool = True):
    path = Path(filepath) if isinstance(filepath, str) else filepath

    if path.suffix != ".xml":
        raise ValueError(
            f"Unsupported file format: {path.suffix}. Only .xml files are supported."
        )

    dsbXML = _get_dsbXML()
    if use_cache:
        dsb = _cached_load_model_internal(str(path.resolve()))
    else:
        with open(path, "rb") as f:
            dsb = dsbXML.from_xml(f.read())

    if dsb.site:
        set_site_counter(dsb.site.handle)
    return dsb

clear_model_cache()

Source code in dsbxml\utils.py
42
43
def clear_model_cache():
    _cached_load_model_internal.cache_clear()

save_model(model, filepath)

Source code in dsbxml\utils.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def save_model(model, filepath: str | Path) -> None:
    path = Path(filepath) if isinstance(filepath, str) else filepath

    if path.suffix != ".xml":
        raise ValueError(
            f"Unsupported file format: {path.suffix}. Only .xml files are supported."
        )

    xml_output = model.to_xml()
    with open(path, "wb") as f:
        if isinstance(xml_output, bytes):
            f.write(xml_output)
        else:
            f.write(xml_output.encode("utf-8"))

validate_against_xsd(source)

Check a model, an XML file path or XML bytes against DesignBuilder.xsd.

Returns the schema's error messages; an empty list means the XML is valid. A loaded model is serialised first, so this also tells whether saving it would produce a file DesignBuilder's schema accepts.

Source code in dsbxml\utils.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def validate_against_xsd(source) -> list[str]:
    """Check a model, an XML file path or XML bytes against DesignBuilder.xsd.

    Returns the schema's error messages; an empty list means the XML is valid.
    A loaded model is serialised first, so this also tells whether saving it
    would produce a file DesignBuilder's schema accepts.
    """
    from lxml import etree

    if isinstance(source, (str, Path)):
        document = etree.parse(str(source))
    else:
        xml = source if isinstance(source, bytes) else source.to_xml()
        xml = xml if isinstance(xml, bytes) else xml.encode("utf-8")
        document = etree.fromstring(xml).getroottree()
    schema = _xsd_schema()
    schema.validate(document)
    # lxml's error_log is a C extension type pylint cannot see is iterable.
    return [error.message for error in schema.error_log]  # pylint: disable=not-an-iterable

Comparing models

Semantic diff between two loaded models.

Reports added/removed buildings, zones, surfaces, and openings, changed attributes (old -> new), and HVAC topology changes. Handle/index fields on ObjectIDs (handle, buildingHandle, buildingBlockHandle, zoneHandle, surfaceIndex, openingIndex) are ignored throughout — DesignBuilder renumbers these on every save, so they're noise, not a semantic change.

ModelDiff dataclass

Source code in dsbxml\diffing.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@dataclass
class ModelDiff:
    added: dict[str, list] = field(default_factory=dict)
    removed: dict[str, list] = field(default_factory=dict)
    attribute_changes: list[dict] = field(default_factory=list)

    @property
    def has_changes(self) -> bool:
        return bool(self.added or self.removed or self.attribute_changes)

    def summary(self) -> str:
        lines = []
        for label, items in self.added.items():
            lines.append(f"+ {len(items)} {label} added")
        for label, items in self.removed.items():
            lines.append(f"- {len(items)} {label} removed")
        for change in self.attribute_changes:
            lines.append(f"~ {change['path']}: {change['old']!r} -> {change['new']!r}")
        return "\n".join(lines) if lines else "No semantic changes"

added = field(default_factory=dict) class-attribute instance-attribute

removed = field(default_factory=dict) class-attribute instance-attribute

attribute_changes = field(default_factory=list) class-attribute instance-attribute

has_changes property

__init__(added=dict(), removed=dict(), attribute_changes=list())

summary()

Source code in dsbxml\diffing.py
64
65
66
67
68
69
70
71
72
def summary(self) -> str:
    lines = []
    for label, items in self.added.items():
        lines.append(f"+ {len(items)} {label} added")
    for label, items in self.removed.items():
        lines.append(f"- {len(items)} {label} removed")
    for change in self.attribute_changes:
        lines.append(f"~ {change['path']}: {change['old']!r} -> {change['new']!r}")
    return "\n".join(lines) if lines else "No semantic changes"

diff_models(model_a, model_b)

Compare two dsbXML models, ignoring handle/index renumbering.

Source code in dsbxml\diffing.py
137
138
139
140
141
def diff_models(model_a, model_b) -> ModelDiff:
    """Compare two dsbXML models, ignoring handle/index renumbering."""
    diff = ModelDiff()
    _diff_value(model_a.model_dump(), model_b.model_dump(), [], diff)
    return diff

Errors

Validation error formatting with model context (building/zone/surface).

Pydantic's default ValidationError shows the field path as raw indices (site.buildings.building.0...zones.zone.3...surfaces.surface.2.area), which doesn't say which building or zone that is without cross-referencing the source file by hand. ModelValidationError re-walks the original XML tree along that same path and adds the building title / zone handle / surface index actually found there.

ModelValidationError

Bases: ValueError

Wraps a pydantic ValidationError, adding model context to each error.

Falls back to pydantic's own field path when the source XML tree isn't available, or an error's path leaves the mapped building/zone/surface hierarchy (e.g. HVAC fields).

Source code in dsbxml\errors.py
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
class ModelValidationError(ValueError):
    """Wraps a pydantic ValidationError, adding model context to each error.

    Falls back to pydantic's own field path when the source XML tree isn't
    available, or an error's path leaves the mapped building/zone/surface
    hierarchy (e.g. HVAC fields).
    """

    def __init__(self, original: ValidationError, root=None):
        self.original = original
        self.errors = original.errors()
        super().__init__(self._format(root))

    def _format(self, root) -> str:
        lines = [f"{len(self.errors)} validation error(s) for {self.original.title}:"]
        for error in self.errors:
            loc = error.get("loc", ())
            crumb = _breadcrumb(loc, root)
            field = loc[-1] if loc else "?"
            path = ".".join(str(part) for part in loc)
            if crumb:
                lines.append(f"  {crumb} > {field}: {error['msg']} ({path})")
            else:
                lines.append(f"  {path}: {error['msg']}")
        return "\n".join(lines)

original = original instance-attribute

errors = original.errors() instance-attribute

__init__(original, root=None)

Source code in dsbxml\errors.py
111
112
113
114
def __init__(self, original: ValidationError, root=None):
    self.original = original
    self.errors = original.errors()
    super().__init__(self._format(root))

Identifiers and handles

ObjectIDs

Bases: BaseModel

Source code in dsbxml\id.py
30
31
32
33
34
35
36
37
38
39
40
class ObjectIDs(BaseModel):
    handle: int = attr(default_factory=generate_site_handle)
    buildingHandle: int = attr(default=-1)
    buildingBlockHandle: int = attr(default=-1)
    zoneHandle: int = attr(default=-1)
    surfaceIndex: int = attr(default=-1)
    openingIndex: int = attr(default=-1)

    model_config = ConfigDict(
        populate_by_name=True,
    )

handle = attr(default_factory=generate_site_handle) class-attribute instance-attribute

buildingHandle = attr(default=(-1)) class-attribute instance-attribute

buildingBlockHandle = attr(default=(-1)) class-attribute instance-attribute

zoneHandle = attr(default=(-1)) class-attribute instance-attribute

surfaceIndex = attr(default=(-1)) class-attribute instance-attribute

openingIndex = attr(default=(-1)) class-attribute instance-attribute

model_config = ConfigDict(populate_by_name=True) class-attribute instance-attribute

current_site_handle()

Source code in dsbxml\id.py
13
14
def current_site_handle() -> int:
    return _site_counter

generate_site_handle()

Source code in dsbxml\id.py
17
18
19
20
21
def generate_site_handle() -> int:
    global _site_counter
    with _site_counter_lock:
        _site_counter += 1
        return _site_counter - 1

set_site_counter(value)

Source code in dsbxml\id.py
24
25
26
27
def set_site_counter(value: int) -> None:
    global _site_counter
    with _site_counter_lock:
        _site_counter = value

Attributes

NameAttribute

Bases: BaseModel

Source code in dsbxml\attributes.py
 8
 9
10
class NameAttribute(BaseModel):
    name: str = attr()
    value: str | None = None

name = attr() class-attribute instance-attribute

value = None class-attribute instance-attribute

KeyAttribute

Bases: BaseModel

Source code in dsbxml\attributes.py
13
14
15
class KeyAttribute(BaseModel):
    key: str = attr()
    value: str | None = None

key = attr() class-attribute instance-attribute

value = None class-attribute instance-attribute

NameAttributes

Bases: BaseModel

Source code in dsbxml\attributes.py
18
19
class NameAttributes(BaseModel):
    attribute: list[NameAttribute] = element(tag="Attribute", default_factory=list)

attribute = element(tag='Attribute', default_factory=list) class-attribute instance-attribute

KeyAttributes

Bases: BaseModel

Source code in dsbxml\attributes.py
22
23
class KeyAttributes(BaseModel):
    attribute: list[KeyAttribute] = element(tag="Attribute", default_factory=list)

attribute = element(tag='Attribute', default_factory=list) class-attribute instance-attribute

HVACAttributeList

Bases: BaseModel

Source code in dsbxml\attributes.py
26
27
28
29
30
class HVACAttributeList(BaseModel):
    buildingZoneHandle: str = attr()
    attributes: NameAttributes = element(
        tag="Attributes", default_factory=lambda: NameAttributes()
    )

buildingZoneHandle = attr() class-attribute instance-attribute

attributes = element(tag='Attributes', default_factory=(lambda: NameAttributes())) class-attribute instance-attribute

ZoneComponentAttributeList

Bases: BaseModel

Source code in dsbxml\attributes.py
33
34
35
36
class ZoneComponentAttributeList(BaseModel):
    hvac_attribute_list: list[HVACAttributeList] = element(
        tag="HVACAttributeList", default_factory=list
    )

hvac_attribute_list = element(tag='HVACAttributeList', default_factory=list) class-attribute instance-attribute

Geometry

Point3D

Bases: BaseModel

Source code in dsbxml\geometry.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Point3D(BaseModel):
    value: str = "0;0;0"

    @field_validator("value", mode="before")
    @classmethod
    def _coerce_empty(cls, v):
        """Treat empty or whitespace-only text as the origin sentinel."""
        if not v or not str(v).strip():
            return "0;0;0"
        return v

    def _parse_coords(self) -> tuple[float, float, float]:
        parsed = tuple(float(c) for c in self.value.split(";"))
        if len(parsed) != 3:
            raise ValueError(f"Expected 3 coordinates, got {len(parsed)}: {self.value!r}")
        return parsed

    @property
    def x(self) -> float:
        return self._parse_coords()[0]

    @property
    def y(self) -> float:
        return self._parse_coords()[1]

    @property
    def z(self) -> float:
        return self._parse_coords()[2]

    @property
    def coords(self) -> list[float]:
        return list(self._parse_coords())

    @property
    def is_zero(self) -> bool:
        """True when all coordinates are zero — the sentinel for 'no position'."""
        return self.value == "0;0;0" or all(c == 0.0 for c in self._parse_coords())

    def __setattr__(self, name: str, value: float | list[float]) -> None:
        if name == "coords":
            if isinstance(value, list) and len(value) == 3:
                self.value = ";".join(map(str, value))
            else:
                raise ValueError("Coordinates must be a list of 3 numbers")
        elif name in ["x", "y", "z"]:
            index = {"x": 0, "y": 1, "z": 2}[name]
            coords = self.value.split(";")
            coords[index] = str(value)
            self.value = ";".join(coords)
        else:
            super().__setattr__(name, value)

value = '0;0;0' class-attribute instance-attribute

x property

y property

z property

coords property

is_zero property

True when all coordinates are zero — the sentinel for 'no position'.

__setattr__(name, value)

Source code in dsbxml\geometry.py
51
52
53
54
55
56
57
58
59
60
61
62
63
def __setattr__(self, name: str, value: float | list[float]) -> None:
    if name == "coords":
        if isinstance(value, list) and len(value) == 3:
            self.value = ";".join(map(str, value))
        else:
            raise ValueError("Coordinates must be a list of 3 numbers")
    elif name in ["x", "y", "z"]:
        index = {"x": 0, "y": 1, "z": 2}[name]
        coords = self.value.split(";")
        coords[index] = str(value)
        self.value = ";".join(coords)
    else:
        super().__setattr__(name, value)

Vertices

Bases: BaseModel

Source code in dsbxml\geometry.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class Vertices(BaseModel):
    point_3d: list[Point3D] = element(tag="Point3D", default_factory=list)

    def __iter__(self) -> Iterator[Point3D]:
        return iter(self.point_3d)

    def __getitem__(self, index: int) -> Point3D:
        return self.point_3d[index]

    def __setitem__(self, index: int, value: str | Point3D) -> None:
        try:
            if isinstance(value, Point3D):
                self.point_3d[index] = value
            elif isinstance(value, str):
                self.point_3d[index] = Point3D(value=value)
        except IndexError as e:
            raise ValueError(f"Invalid index {index} for Vertices.point_3d") from e

point_3d = element(tag='Point3D', default_factory=list) class-attribute instance-attribute

__iter__()

Source code in dsbxml\geometry.py
69
70
def __iter__(self) -> Iterator[Point3D]:
    return iter(self.point_3d)

__getitem__(index)

Source code in dsbxml\geometry.py
72
73
def __getitem__(self, index: int) -> Point3D:
    return self.point_3d[index]

__setitem__(index, value)

Source code in dsbxml\geometry.py
75
76
77
78
79
80
81
82
def __setitem__(self, index: int, value: str | Point3D) -> None:
    try:
        if isinstance(value, Point3D):
            self.point_3d[index] = value
        elif isinstance(value, str):
            self.point_3d[index] = Point3D(value=value)
    except IndexError as e:
        raise ValueError(f"Invalid index {index} for Vertices.point_3d") from e

HandlePoint

Bases: BaseModel

Source code in dsbxml\geometry.py
85
86
87
88
89
class HandlePoint(BaseModel):
    point_3d: Point3D = element(tag="Point3D")

    def __iter__(self) -> Iterator[Point3D]:
        return iter([self.point_3d])

point_3d = element(tag='Point3D') class-attribute instance-attribute

__iter__()

Source code in dsbxml\geometry.py
88
89
def __iter__(self) -> Iterator[Point3D]:
    return iter([self.point_3d])

WrappedPoint3D

Bases: BaseModel

A Point3D nested one level deeper under its own child tag.

Most single-coordinate fields in the DesignBuilder XML (Origin, Coordinate, Begin, End, ControlPoint, ...) are not the coordinate text themselves but a wrapper element containing a single child, e.g. 1;2;3. Typing these fields as plain Point3D silently parses to the "0;0;0" default, since pydantic-xml looks for the coordinate text directly on the wrapper element rather than recursing into the nested tag. Exposes the same x/y/z/coords/ is_zero interface as Point3D so existing call sites are unaffected.

Source code in dsbxml\geometry.py
 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
class WrappedPoint3D(BaseModel):
    """A Point3D nested one level deeper under its own <Point3D> child tag.

    Most single-coordinate fields in the DesignBuilder XML (Origin,
    Coordinate, Begin, End, ControlPoint, ...) are not the coordinate text
    themselves but a wrapper element containing a single <Point3D> child,
    e.g. <Origin><Point3D>1;2;3</Point3D></Origin>. Typing these fields as
    plain Point3D silently parses to the "0;0;0" default, since pydantic-xml
    looks for the coordinate text directly on the wrapper element rather
    than recursing into the nested tag. Exposes the same x/y/z/coords/
    is_zero interface as Point3D so existing call sites are unaffected.
    """

    point_3d: Point3D = element(tag="Point3D", default_factory=Point3D)

    @property
    def x(self) -> float:
        return self.point_3d.x

    @property
    def y(self) -> float:
        return self.point_3d.y

    @property
    def z(self) -> float:
        return self.point_3d.z

    @property
    def coords(self) -> list[float]:
        return self.point_3d.coords

    @property
    def is_zero(self) -> bool:
        return self.point_3d.is_zero

point_3d = element(tag='Point3D', default_factory=Point3D) class-attribute instance-attribute

x property

y property

z property

coords property

is_zero property

Range

Bases: BaseModel

Source code in dsbxml\geometry.py
128
129
130
class Range(BaseModel):
    org: WrappedPoint3D = element(tag="Org")
    end: WrappedPoint3D = element(tag="End")

org = element(tag='Org') class-attribute instance-attribute

end = element(tag='End') class-attribute instance-attribute

Line

Bases: BaseModel

Source code in dsbxml\geometry.py
133
134
135
136
137
138
class Line(BaseModel):
    object_ids: Annotated[ObjectIDs, Field(default_factory=ObjectIDs)] = element(
        tag="ObjectIDs"
    )
    begin: WrappedPoint3D = element(tag="Begin")
    end: WrappedPoint3D = element(tag="End")

object_ids = element(tag='ObjectIDs') class-attribute instance-attribute

begin = element(tag='Begin') class-attribute instance-attribute

end = element(tag='End') class-attribute instance-attribute

ImageRectangle

Bases: BaseModel

Source code in dsbxml\geometry.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
class ImageRectangle(BaseModel):
    object_ids: Annotated[ObjectIDs, Field(default_factory=ObjectIDs)] = element(
        tag="ObjectIDs"
    )
    imageTextureIndex: int = element(tag="ImageTextureIndex")
    maskTextureIndex: int = element(tag="MaskTextureIndex")
    selectedImageTextureIndex: int = element(tag="SelectedImageTextureIndex")
    inactiveImageTextureIndex: int = element(tag="InactiveImageTextureIndex")
    textured: str = element(tag="Textured")
    masked: str = element(tag="Masked")
    selectedImage: str = element(tag="SelectedImage")
    inactiveImage: str = element(tag="InactiveImage")
    color: str = element(tag="Color")
    active: str = element(tag="Active")
    vertices: Vertices = element(tag="Vertices")
    range: Range | None = element(tag="Range", default=None)

object_ids = element(tag='ObjectIDs') class-attribute instance-attribute

imageTextureIndex = element(tag='ImageTextureIndex') class-attribute instance-attribute

maskTextureIndex = element(tag='MaskTextureIndex') class-attribute instance-attribute

selectedImageTextureIndex = element(tag='SelectedImageTextureIndex') class-attribute instance-attribute

inactiveImageTextureIndex = element(tag='InactiveImageTextureIndex') class-attribute instance-attribute

textured = element(tag='Textured') class-attribute instance-attribute

masked = element(tag='Masked') class-attribute instance-attribute

selectedImage = element(tag='SelectedImage') class-attribute instance-attribute

inactiveImage = element(tag='InactiveImage') class-attribute instance-attribute

color = element(tag='Color') class-attribute instance-attribute

active = element(tag='Active') class-attribute instance-attribute

vertices = element(tag='Vertices') class-attribute instance-attribute

range = element(tag='Range', default=None) class-attribute instance-attribute

SegmentList

Bases: BaseModel

Source code in dsbxml\geometry.py
159
160
161
class SegmentList(BaseModel):
    # Real files have both populated and empty (<SegmentList></SegmentList>) forms.
    line_array: LineArray | None = element(tag="LineArray", default=None)

line_array = element(tag='LineArray', default=None) class-attribute instance-attribute

LineArray

Bases: BaseModel

Source code in dsbxml\geometry.py
164
165
class LineArray(BaseModel):
    line: list[Line] = element(tag="Line")

line = element(tag='Line') class-attribute instance-attribute

Tables

Table

Bases: BaseModel

Source code in dsbxml\tables.py
 8
 9
10
11
12
13
class Table(BaseModel):
    name: str = attr()
    numberOfFields: int = attr()
    category: list[str] = element(tag="Category", default_factory=list)
    field_name: list[str] = element(tag="FieldName", default_factory=list)
    row: list[str] = element(tag="Row", default_factory=list)

name = attr() class-attribute instance-attribute

numberOfFields = attr() class-attribute instance-attribute

category = element(tag='Category', default_factory=list) class-attribute instance-attribute

field_name = element(tag='FieldName', default_factory=list) class-attribute instance-attribute

row = element(tag='Row', default_factory=list) class-attribute instance-attribute

Tables

Bases: BaseModel

Source code in dsbxml\tables.py
16
17
18
19
20
21
22
23
class Tables(BaseModel):
    table: list[Table] = element(tag="Table", default_factory=list)

    def get_table_by_name(self, name: str) -> Table:
        table_dict = {t.name: t for t in self.table}
        if name not in table_dict:
            raise KeyError(f"Table '{name}' not found")
        return table_dict[name]

table = element(tag='Table', default_factory=list) class-attribute instance-attribute

get_table_by_name(name)

Source code in dsbxml\tables.py
19
20
21
22
23
def get_table_by_name(self, name: str) -> Table:
    table_dict = {t.name: t for t in self.table}
    if name not in table_dict:
        raise KeyError(f"Table '{name}' not found")
    return table_dict[name]

Base model

XSDFloat = Annotated[float, PlainSerializer(_format_decimal, return_type=str, when_used='json')] module-attribute

BaseModel

Bases: BaseXmlModel

Base XML model with unordered element search.

UNORDERED: pydantic-xml's default ORDERED mode consumes elements sequentially, so any field that scans past a later-appearing tag makes it invisible to subsequent fields. UNORDERED finds every element by tag name regardless of position — required because DesignBuilder XML places the same tags in different orders across component types.

Source code in dsbxml\base.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class BaseModel(BaseXmlModel, search_mode=SearchMode.UNORDERED):
    """Base XML model with unordered element search.

    UNORDERED: pydantic-xml's default ORDERED mode consumes elements
    sequentially, so any field that scans past a later-appearing tag makes
    it invisible to subsequent fields. UNORDERED finds every element by tag
    name regardless of position — required because DesignBuilder XML places
    the same tags in different orders across component types.
    """

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        str_strip_whitespace=True,
        slots=True,
    )

    @classmethod
    def _built(cls) -> None:
        """Build the class's schema now if import left it for first use (see __init__.py)."""
        if cls.__xml_serializer__ is None:
            import dsbxml

            dsbxml._load_core_module()  # pylint: disable=protected-access
            cls.model_rebuild()

    @classmethod
    def from_xml_tree(cls, root, *args, **kwargs):
        cls._built()
        return super().from_xml_tree(root, *args, **kwargs)

    def to_xml_tree(self, **kwargs):
        """Serialise without unset optional values.

        pydantic-xml writes an unset optional attribute as ``name=""`` and an
        unset optional primitive element as an empty tag, both invalid
        against the schema. Empty strings and empty containers are not None
        and are still written.
        """
        kwargs.setdefault("exclude_none", True)
        type(self)._built()
        return super().to_xml_tree(**kwargs)

    def to_xml(self, **kwargs):
        """Serialise to XML text; see to_xml_tree for the unset-value handling."""
        kwargs.setdefault("exclude_none", True)
        return super().to_xml(**kwargs)

model_config = ConfigDict(populate_by_name=True, validate_assignment=True, str_strip_whitespace=True, slots=True) class-attribute instance-attribute

from_xml_tree(root, *args, **kwargs) classmethod

Source code in dsbxml\base.py
54
55
56
57
@classmethod
def from_xml_tree(cls, root, *args, **kwargs):
    cls._built()
    return super().from_xml_tree(root, *args, **kwargs)

to_xml_tree(**kwargs)

Serialise without unset optional values.

pydantic-xml writes an unset optional attribute as name="" and an unset optional primitive element as an empty tag, both invalid against the schema. Empty strings and empty containers are not None and are still written.

Source code in dsbxml\base.py
59
60
61
62
63
64
65
66
67
68
69
def to_xml_tree(self, **kwargs):
    """Serialise without unset optional values.

    pydantic-xml writes an unset optional attribute as ``name=""`` and an
    unset optional primitive element as an empty tag, both invalid
    against the schema. Empty strings and empty containers are not None
    and are still written.
    """
    kwargs.setdefault("exclude_none", True)
    type(self)._built()
    return super().to_xml_tree(**kwargs)

to_xml(**kwargs)

Serialise to XML text; see to_xml_tree for the unset-value handling.

Source code in dsbxml\base.py
71
72
73
74
def to_xml(self, **kwargs):
    """Serialise to XML text; see to_xml_tree for the unset-value handling."""
    kwargs.setdefault("exclude_none", True)
    return super().to_xml(**kwargs)