Home > Software design >  Is encoding XML in Go using "innerxml" only meant to be used with certain types?
Is encoding XML in Go using "innerxml" only meant to be used with certain types?

Time:10-20

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.

CodePudding user response:

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.
  • Related