Parsing XML with golang

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

  <body>Hello brother, how are you!</body>  
package main
import (
func main() {

	xmlFile, err := os.Open("records.xml")

	if err != nil {
		fmt.Println("error :",err)
	fmt.Println("Successfully Opened records.xml")
	defer xmlFile.Close()
	type Email struct {
		To      string xml:"to"
		From    string xml:"from"
		Heading string xml:"heading"
		Body    string xml:"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)



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!

Leave a Comment