Search code examples
goserializationreflection

xml.Unmarshal unsupported type struct


I'm getting an error where I cannot xml.Marshal a struct made at runtime with reflect.

It is giving me the following error:

xml: unsupported type: struct { ... }

Here is my go-playground link.

Anyone have any idea why this isn't working?
What am I missing about the implementation?
It works fine for JSON and YAML.


Solution

  • https://pkg.go.dev/encoding/xml@go1.20.3#Marshal

    The name for the XML elements is taken from, in order of preference:

    • the tag on the XMLName field, if the data is a struct
    • the value of the XMLName field of type Name
    • the tag of the struct field used to obtain the data
    • the name of the struct field used to obtain the data
    • the name of the marshaled type

    Your root struct is unnamed and has no XMLName field, therefore the XML marshaler is unable to resolve the root element's name. If you rename the Person xml.Name field to XMLName then to serializer works.

    https://go.dev/play/p/gRH3Y-PUxl8