Closed samholvi closed 3 months ago
@samholvi Hi,
Namespaces and namespace maps are not inherited by submodels. In your case SomethingElse3
doesn't have any namespace, it must be declared explicitly for each model:
from pydantic_xml import BaseXmlModel
NSMAP = {
"something": "urn:something:something:v1",
}
class SomethingElse3(BaseXmlModel, tag='SomethingElse3', ns="something"):
SomethingElse4: str
class SomethingElse2(BaseXmlModel, tag='SomethingElse2', ns="something", nsmap=NSMAP):
SomethingElse3: SomethingElse3
class Something(BaseXmlModel, tag="SomethingElse", ns="something", nsmap=NSMAP):
SomethingElse2: SomethingElse2
something = Something(
SomethingElse2=SomethingElse2(
SomethingElse3=SomethingElse3(
SomethingElse4="ABC"
)
)
)
print(something.to_xml(pretty_print=True).decode())
<something:SomethingElse xmlns:something="urn:something:something:v1">
<something:SomethingElse2>
<something:SomethingElse3>ABC</something:SomethingElse3>
</something:SomethingElse2>
</something:SomethingElse>
Hi! Thank you, that works!
I definitely tried many combinations of parameters, but didn't think it could be missing nsmap
as it works for second level elements without specifying nsmap
but not for 3-rd and following.
Also what maybe confused me is that part of doc "Xml default namespace is a namespace that is applied to the element and all its sub-elements without explicit definition." from https://pydantic-xml.readthedocs.io/en/latest/pages/misc.html#default-namespace.
Made me think the namespace will be inherited.
But the issue is not an issue anymore then. Thank you.
Hi,
First of all thank you for a great software! And then I experience some problem with parsing XML document with elements with namespace. So I have that code and models (`test.py'):
And I have 2 XML files.
input_ok.xml
and
input_error_xml
The only difference between those is that the
SomethingElse3
element is namespaces ininput_error_xml
Executing
python test.py input_ok.xml
works ok and gives me output:But executing
python test.py input_error.xml
gives and error below:So if I introduce any element fro level 3 with namespace the error will arise. I tried few different ways of defining models and model fields, with namespaces and not. But nothing helped. Maybe someone is able to figure out is that something wrong with how I define models or is there a bug.
===
Also, the same behaviour works other way, i.e. when generating an XML from model.
test2.py
Executing
python test2.py
gives,. whereSomethingElse3
is also without namespace: