Golang supports an API that handles XML using encoding/xml package for reading XML files. os package for open the file. xml.Unmarshal()
used for decoding.
create file records.xml
<email> <to>Vimal</to> <from>Sonoo</from> <heading>Hello</heading> <body>Hello brother, how are you!</body> </email>
package main import ( "fmt" "encoding/xml" "io/ioutil" "os" ) func main() { xmlFile, err := os.Open("records.xml") if err != nil { fmt.Println("error :",err) return } fmt.Println("Successfully Opened records.xml") defer xmlFile.Close() type Email struct { To stringxml:"to"
From stringxml:"from"
Heading stringxml:"heading"
Body stringxml:"body"
} byteValue, _ := ioutil.ReadAll(xmlFile) //read byte value from xmlFile var email Email xml.Unmarshal(byteValue, &email) fmt.Println("To: ",email.To) fmt.Println("From: ",email.From) fmt.Println("Heading: ",email.Heading) fmt.Println("Body: ",email.Body) }
Output
xyz@xyz:~/Documents/golang _practices$ go build xyz@xyz:~/Documents/golang _practices$ go run csv.go Successfully Opened records.xml To: Vimal From: Sonoo Heading: Hello Body: Hello brother, how are you!