I am using the encoding/xml package in Go and the Encoder example code.
While I am able to produce workable XML, I am unable to add all of the attributes that I need.
As an example, let us use the concept of temperature reporting. What I need is something like this:
<environment>
<temperature type="float" units="c">-11.3</temperature>
</environment>
My struct looks like this:
type climate struct {
XMLName xml.Name `xml:"environment"`
Temperature string `xml:"temperature"`
Type string `xml:"type,attr"`
Units string `xml:"unit,attr"`
}
What I end up with looks like this:
<environment type="float" unit="c">
<temperature>-11.3</temperature>
</environment>
My example code in the Go Playground
How can I format the struct tags to put the attributes in the proper element?
Your desired XML has 2 elements: <environment>
and <temperature>
, so you should have 2 types (structs) to model them. And you may use the tag ",chardata"
to tell the encoder to write the field's value as character data and not as an XML element.
type environment struct {
Temperature temperature `xml:"temperature"`
}
type temperature struct {
Temperature string `xml:",chardata"`
Type string `xml:"type,attr"`
Units string `xml:"unit,attr"`
}
Testing it:
x := &environment{
Temperature: temperature{Temperature: "-11.3", Type: "float", Units: "c"},
}
enc := xml.NewEncoder(os.Stdout)
enc.Indent("", " ")
if err := enc.Encode(x); err != nil {
fmt.Printf("error: %v\n", err)
}
It produces the desired output (try it on the Go Playground):
<environment>
<temperature type="float" unit="c">-11.3</temperature>
</environment>
Note that you get the same result if you use the ",innerxml"
tag which tells the encoder to write the value verbatim, not subject to the usual marshaling procedure:
type temperature struct {
Temperature string `xml:",innerxml"`
Type string `xml:"type,attr"`
Units string `xml:"unit,attr"`
}
Output is the same. Try this one on the Go Playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With