在Go中使用”innerxml”对XML进行编码,是否只适用于特定类型?

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

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'关联的值(参见上面的示例)。

  • 如果结构体具有类型为[]bytestring且标签为",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.

huangapple
  • 本文由 发表于 2022年10月19日 22:50:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/74127494.html
匿名

发表评论

匿名网友

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

确定