This Go code demonstrates the use of the encoding/xml package for encoding and decoding XML data. Let's go through the code with inline comments and explanations:
// Importing necessary packages.
import (
"encoding/xml"
"fmt"
)
// Struct definition for the Plant with XML tags.
type Plant struct {
XMLName xml.Name `xml:"plant"`
Id int `xml:"id,attr"`
Name string `xml:"name"`
Origin []string `xml:"origin"`
}
// String method for Plant to customize its string representation.
func (p Plant) String() string {
return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
p.Id, p.Name, p.Origin)
}
// The main function, where the execution of the program begins.
func main() {
// Creating a Plant instance (coffee) and encoding it to XML.
coffee := &Plant{Id: 27, Name: "Coffee"}
coffee.Origin = []string{"Ethiopia", "Brazil"}
// Encoding the Plant to XML with indentation.
out, _ := xml.MarshalIndent(coffee, " ", " ")
fmt.Println(string(out))
// Printing XML with header.
fmt.Println(xml.Header + string(out))
// Decoding XML back into a Plant instance.
var p Plant
if err := xml.Unmarshal(out, &p); err != nil {
panic(err)
}
fmt.Println(p)
// Creating another Plant instance (tomato) and adding it to a nested structure.
tomato := &Plant{Id: 81, Name: "Tomato"}
tomato.Origin = []string{"Mexico", "California"}
// Defining a struct with nested Plants and encoding it to XML.
type Nesting struct {
XMLName xml.Name `xml:"nesting"`
Plants []*Plant `xml:"parent>child>plant"`
}
nesting := &Nesting{}
nesting.Plants = []*Plant{coffee, tomato}
// Encoding the nested structure to XML with indentation.
out, _ = xml.MarshalIndent(nesting, " ", " ")
fmt.Println(string(out))
}