xml.Unmarshal不支持类型struct。

huangapple go评论220阅读模式
英文:

xml.Unmarshal unsupported type struct

问题

我遇到了一个错误,无法使用reflect在运行时对结构体进行xml.Marshal。

它给出了以下错误:

xml: unsupported type: struct { ... }

这是我的go-playground链接链接

有人知道为什么这不起作用吗?
我在实现上漏掉了什么?
对于JSON和YAML,它运行良好。

英文:

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.

答案1

得分: 3

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

> XML元素的名称取自以下优先顺序:
>
> - 如果数据是结构体,则取自XMLName字段的标签
> - 如果数据是Name类型的XMLName字段,则取自XMLName字段的值
> - 用于获取数据的结构体字段的标签
> - 用于获取数据的结构体字段的名称
> - 序列化类型的名称

你的_root_结构体是_无名字的_,并且没有XMLName字段,因此XML编组器无法解析根元素的名称。如果你将Person xml.Name字段重命名为XMLName,那么序列化器就能正常工作。

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

英文:

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

huangapple
  • 本文由 发表于 2023年5月12日 17:30:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76234942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定