xsdata icon indicating copy to clipboard operation
xsdata copied to clipboard

Meta attribute of child elements not used

Open snorfalorpagus opened this issue 4 weeks ago • 1 comments

It seems the Meta attribute of an element that is not the root node is ignored when being serialized.

For example, the code below produces the following output:

<ns0:Parent xmlns:ns0="xyz"><child>foobar</child></ns0:Parent>

Rather than what I expected:

<ns0:Parent xmlns:ns0="xyz"><ns1:SomeChild xmlns:ns1="abc">foobar</ns1:SomeChild></ns0:Parent>

If I explicitly use field(metadata=...) on the child element I can get it to work, but why is this required? Is this a design choice rather than a bug? If so is there a way to enable what I expect with a flag somewhere?

from dataclasses import dataclass, field

from xsdata.formats.dataclass.serializers import XmlSerializer


@dataclass
class Child:
    class Meta:
        name = "SomeChild"
        namespace = "abc"

    name: str


@dataclass
class Parent:
    class Meta:
        namespace = "xyz"

    child: Child  # = field(metadata=Child.Meta.__dict__)


parent = Parent(child=Child(name="foobar"))


result = XmlSerializer().render(parent)
print(result)

snorfalorpagus avatar Dec 04 '25 13:12 snorfalorpagus

Yes, this is by design. xsdata only automatically applies a dataclass Meta.name/Meta.namespace when it is the document root or when the field is explicitly configured with that metadata.

For nested elements the field name (child) is used by default, and the target element name/namespace must be declared at the usage site — exactly like in XSD where the element reference defines the name and namespace, not the type itself.

tefra avatar Dec 04 '25 17:12 tefra