Golang ProgramsGolang Programs

Golang write struct to XML file

The xml package has an Marshal() function which is used to serialized values from a struct and write them to a file in XML format.
package main
 
import (
	"encoding/xml"
	"io/ioutil"
)
 
type notes struct {
	To      string `xml:"to"`
	From    string `xml:"from"`
	Heading string `xml:"heading"`
	Body    string `xml:"body"`
}
 
func main() {
	note := &notes{To: "Nicky",
		From:    "Rock",
		Heading: "Meeting",
		Body:    "Meeting at 5pm!",
	}
 
	file, _ := xml.MarshalIndent(note, "", " ")
 
	_ = ioutil.WriteFile("notes1.xml", file, 0644)
 
}

The notes struct is defined with an uppercase first letter and ″xml″ field tags are used to identify the keys. The struct values are initialized and then serialize with the xml.Marshal() function. The serialized XML formatted byte slice is received which then written to a file using the ioutil.WriteFile() function.