encoding/xml: cannot unmarshal into without struct tags #65099
Labels
NeedsInvestigation
Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
Milestone
Go version
go version go1.21.6 linux/amd64
Output of
go env
in your module/workspace:What did you do?
I'm filing this one as a bug since the behaviour took me by surprise and wasn't obvious to me from the documentation on encoding/xml.Unmashal.
I tried to decode a response into a struct where:
XMLName
setI've included the full code in a Gist, because unfortunately
go.dev/play
continuously returns server errors when using the "Share" button: https://gist.github.com/daenney/07e546e0c9d26e5ba183feadd3ba00c4What did you see happen?
Whether a single, or multiple
<a>
elements are present,.Data
remains empty, whereas I expected it to accumulate into.Data
given theXMLName
is present on the slice member struct.What did you expect to see?
It feels like the following two things should be equivalent and behave the same:
Clearly they're not since
[]A3
doesn't directly have a tag and it seems the implementation doesn't take theXMLName
of the slice members into account. It's not obvious from the documentation that in the case of a slice either the member name or the struct tag needs to match the XML element name for the decoding to occur. Even if I create a named type liketype Datas []T
, I can't attach the right xml tag to it nor give it anXMLName
member since it's not a struct.This isn't typically a problem as you can always write the
xml:"a"
tag, until we throw generics in the mix. Many APIs have a envelope, like seen here, with stuff like aninfo
orerror
member in their response and the data elements, where the data elements can be a different type based on the query/endpoint. It would be nice to be able to define something like:There is one, hacky, way to make this work:
Due to the
xml:",any"
we now get the intended behaviour. But this is only safe if the wrappingResponse
type defines all other fields upfront, otherwise different elements could try to accumulate intoResponse.Data
andUnmashal
would fail.The text was updated successfully, but these errors were encountered: