The snippet below,
package main
import (
"encoding/xml"
"fmt"
)
func main() {
var r struct {
Item []struct {
Value string `xml:"value,attr"`
Flag bool `xml:"flag,attr"`
} `xml:"item"`
}
xml.Unmarshal([]byte(`
<result>
<item value="1" flag="false" />
<item value="2" flag="true" />
<item value="3" />
</result>`,
), &r)
fmt.Printf("%+v
", r)
}
Will print the following result:
{Item:[{Value:1 Flag:false} {Value:2 Flag:true} {Value:3 Flag:false}]}
In some elements, flag
attribute will be missing (e.g. item 3 above), but I want it to take the default value of true
, instead than false
.
- I cannot assign it in the constructor, because I don't know the number of elements in the array upfront.
- I cannot use a custom type that implements
UnmarshalerAttr
and assign during unmarshaling because if the attribute is missing,UnmarshalXMLAttr
is not run. - I could make it a pointer, and then check if nil, then true, but that's just gross and error-prone.
How would I go about doing this?