Skip to content

Commit 7d646af

Browse files
committed
doc: sub-model namespace inheritance documented.
1 parent 652025a commit 7d646af

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

docs/source/pages/data-binding/elements.rst

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,39 @@ The namespace and namespace mapping can be declared for a model. In that case al
153153
:start-after: json-start
154154
:end-before: json-end
155155

156+
.. note::
157+
**Pay attention** to the namespace inheritance rule: namespace and namespace mapping
158+
are only inherited by primitive types not sub-models. If your sub-model share
159+
the namespace with the parent model you must define it explicitly:
160+
161+
.. code-block:: python
162+
163+
from pydantic_xml import BaseXmlModel, element
164+
165+
NSMAP = {
166+
'co': 'http://www.company.com/co',
167+
}
168+
169+
class SubModel(BaseXmlModel, ns='co', nsmap=NSMAP): # define ns and nsmap explicitly
170+
field2: str = element(tag='element1')
171+
172+
class Model(BaseXmlModel, ns='co', nsmap=NSMAP):
173+
field1: str = element(tag='element1') # ns "co" is inherited by the element
174+
sub: SubModel # ns and nsmap are not inherited by the SubModel
175+
176+
model = Model(field1="value1", sub=SubModel(field2="value2"))
177+
print(model.to_xml(pretty_print=True).decode())
178+
179+
180+
.. code-block:: xml
181+
182+
<co:Model xmlns:co="http://www.company.com/co">
183+
<co:element1>value1</co:element1>
184+
<co:sub>
185+
<co:element1>value2</co:element1>
186+
</co:sub>
187+
</co:Model>
188+
156189
157190
The namespace and namespace mapping can be also applied to model types passing ``ns`` and ``nsmap``
158191
to :py:func:`pydantic_xml.element`. If they are omitted the model namespace and namespace mapping is used:

0 commit comments

Comments
 (0)