Golang program to read XML file into struct
The xml package includes
Unmarshal()
function that supports decoding data from a byte slice into values. The xml.Unmarshal()
function is used to decode the values from the XML formatted file into a Notes
struct.Sample XML file:
Example
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
)
type Notes struct {
To string `xml:"to"`
From string `xml:"from"`
Heading string `xml:"heading"`
Body string `xml:"body"`
}
func main() {
data, _ := ioutil.ReadFile("notes.xml")
note := &Notes{}
_ = xml.Unmarshal([]byte(data), ¬e)
fmt.Println(note.To)
fmt.Println(note.From)
fmt.Println(note.Heading)
fmt.Println(note.Body)
}
Output
Tove
Jani
Reminder
Don't forget me this weekend!
Most Helpful This Week
Undefined reference to <variable/function> error in Golang
Example: How to use ReadFull from IO Package in Golang?
How do you handle HTTP errors in Go?
Golang program to demonstrates how to encode map data into a JSON string.
How to convert String to Boolean Data Type Conversion in Go?
Golang program to print all Permutations of a given string
Illustration of the dining philosophers problem in Golang
Golang program for implementation of Floyd–Warshall Algorithm
Go program to reading plain text files
How to check if an item exists in Slice in Golang?