I have a snippet of XML I need to read and write. It's an array of <condition>
with an <operator>
in between each except for the last entity.
<conditions>
<condition>
<label>a</label>
</condition>
<operator>AND</operator>
<condition>
<label>b</label>
</condition>
<operator>AND</operator>
<condition>
<label>c</label>
</condition>
<conditions>
My Go model looks like this
type Condition struct {
XMLName xml.Name `xml:"condition" json:"-"`
Label string `xml:"label"`
}
type Conditions struct {
ConditionList []Condition `xml:"condition,omitempty"`
Operator string `xml:"operator"`
}
If I marshal the struct the operator only appears once on the bottom. as expected
<Conditions>
<condition>
<label>a</label>
</condition>
<condition>
<label>b</label>
</condition>
<condition>
<label>c</label>
</condition>
<operator>AND</operator>
</Conditions>
How do i get the operator to appear after every condition except for the last one?
The closest i could get was using a wrapper
func (c Conditions) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
type tCondition struct {
XMLName xml.Name `xml:"condition" json:"-"`
Label string `xml:"label"`
}
type tConditionWithOp struct {
XMLName xml.Name `xml:"-" json:"-"`
Condition tCondition `xml: "conditions"`
Operator string `xml:",omitempty"`
}
type tWrapper struct {
OPS []tConditionWithOp
}
lst := make([]tConditionWithOp, 0, 10)
for idx, cond := range c.ConditionList {
tCond := tCondition{
Label: cond.Label,
}
tCondOp := tConditionWithOp{
Condition: tCond,
}
if idx < len(c.ConditionList)-1 {
tCondOp.Operator = c.Operator
}
lst = append(lst, tCondOp)
}
wrapper := tWrapper{
OPS: lst,
}
return e.EncodeElement(wrapper, start)
}
But I now have an <OPS>
tag
<Conditions>
<OPS>
<condition>
<label>a</label>
</condition>
<Operator>AND</Operator>
</OPS>
<OPS>
<condition>
<label>b</label>
</condition>
<Operator>AND</Operator>
</OPS>
<OPS>
<condition>
<label>c</label>
</condition>
</OPS>
</Conditions>
I have created a playground here