英文:
Is encoding XML in Go using "innerxml" only meant to be used with certain types?
问题
当使用xml:"innerxml"
时,我发现结果取决于类型是否为"内联"。
当使用string时,它按预期工作,但将类型更改为int时,值会被包装在另一个标签中。
在Go Playground上有一个最简示例。
我期望生成的XML结构是相同的。
英文:
When using xml:",innerxml"
I see different results depending on the type being "inlined"
When using string it works as expected but changing the type to int the value gets wrapped in another tag.
Minimal example on Go Playground.
I was expected the structure om produced XML to be the same.
答案1
得分: 2
只有当字段的类型为string
或[]byte
时,才能获得所需的输出。这在xml.Marshal()
的文档中没有得到很好的记录,但xml.Unmarshal()
的文档中提到了这一点:
Unmarshal使用以下规则将XML元素映射到结构体。在这些规则中,字段的标签是指结构体字段标签中与键'xml'关联的值(参见上面的示例)。
- 如果结构体具有类型为
[]byte
或string
且标签为",innerxml"的字段,则Unmarshal会将元素内部的原始XML累积到该字段中。其余的规则仍然适用。
英文:
You get your "desired" output only if the field's type is string
or []byte
. This isn't documented at xml.Marshal()
properly, but the documentation of xml.Unmarshal()
does mention it:
> Unmarshal maps an XML element to a struct using the following rules. In the rules, the tag of a field refers to the value associated with the key 'xml' in the struct field's tag (see the example above).
> - If the struct has a field of type []byte or string with tag ",innerxml", Unmarshal accumulates the raw XML nested inside the element in that field. The rest of the rules still apply.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论