reflection - Change struct tag (xml) at runtime -
there's struct:
type s struct { value string `xml:"value,attr"` }
i want encode struct xml file. however, want attribute name of value
different in each file:
s1 := s{ value: "one" }
should encode to:
<s value="one"></s>
and
s2 := s{ value: "two" }
should encode to:
<s category="two"></s>
so, need either change xml element name somehow, or change tag on field. possible?
i checked reflect
(https://golang.org/pkg/reflect/#value.fieldbyname), since fieldbyname
returns value type , there no set
methods, don't think it's possible use reflection.
(i don't know why did other person delete answer, here's mine.)
you can either use combination of ,attr
, ,omitempty
type s struct { value string `xml:"value,attr,omitempty"` category string `xml:"category,attr,omitempty"` }
(playground: http://play.golang.org/p/c9trla80rv) or create custom xml.marshalerattr
type s struct { value val `xml:",attr"` } type val struct{ string } func (v val) marshalxmlattr(name xml.name) (xml.attr, error) { if v.string == "one" { return xml.attr{name: xml.name{local: "value"}, value: v.string}, nil } return xml.attr{name: xml.name{local: "category"}, value: v.string}, nil }
(playground: http://play.golang.org/p/a1wd2gonb_).
the first approach easier less flexible, , makes struct bigger. second approach more complex, more robust , flexible.
Comments
Post a Comment