英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论