I'm trying to unmarshal XML like this in Go:
<property>
<code value="abc"/>
<valueBoolean value="true"/>
</property>
or this
<property>
<code value="abc"/>
<valueString value="apple"/>
</property>
or this
<property>
<code value="abc"/>
<valueDecimal value="3.14159"/>
</property>
etc., into this:
type Property struct {
Code string `xml:"code>value,attr"`
Value interface{}
}
where the tag (valueBoolean
, valueString
, etc.) tells me what the type of the value attribute is. The XML that I'm trying to parse is part of an international standard, so I don't have any control over its definition. It wouldn't be hard to implement parsing these things, something like:
var value string
for a := range se.Attr {
if a.Name.Local == "value" {
value = a.Value
} else {
// Invalid attribute
}
}
switch se.Name.Local {
case "code":
case "valueBoolean":
property.Value = value == "true"
case "valueString":
property.Value = value
case "valueInteger":
property.Value, err = strconv.ParseInteger(value)
case "valueDecimal":
property.Value, err = strconv.ParseFloat(value)
...
}
but I can't figure out how to tell the XML package to find it, and these things are buried in other XML that I'd really rather use xml.Unmarshal
to handle. Alternately, I could redefine the type as:
type Property struct {
Code string `xml:"code>value,attr"`
ValueBoolean bool `xml:"valueBoolean>value,attr"`
ValueString string `xml:"valueString>value,attr"`
ValueInteger int `xml:"valueInteger>value,attr"`
ValueDecimal float `xml:"valueDecimal>value,attr"`
}
but that's pretty inefficient, particularly given that I'll have a large number of instances of these things, and this leaves me no way to derive the type without adding another attribute to indicate the type.
Can I somehow tie this into the normal XML unmarshalling method, just handling the tricky part by hand, or do I need to write the whole unmarshaller for this type from scratch?