Go – Convert an Object to XML in Golang

Hello everyone, in this tutorial, we will show you how to convert an Object to XML in Golang programming language. The example program has been tested and shared in the post.

Converting an Object to XML in Golang
Converting an Object to XML in Golang

Example Program – Object to XML in Golang

package main
import (
"encoding/xml"
"fmt"
"os"
)
type Address struct{
City string
State string
Country string
}
type Employee struct {
Id int
FirstName string
LastName string
Age int
Address Address
Designation string
Salary int
}
func main()  {
emp := Employee{
Id: 101,
FirstName: "Dinesh",
LastName: "Krishnan",
Age: 20,
Designation: "Technology Consultant",
Salary: 120000,
}
emp.Address = Address{
City: "Phoenix",
State: "Arizona",
Country: "USA",
}
output, err := xml.MarshalIndent(emp, "", "  ")
if err != nil {
fmt.Println("Error!")
}
os.Stdout.Write(output)
}

Output

<Employee>
<Id>101</Id>
<FirstName>Dinesh</FirstName>
<LastName>Krishnan</LastName>
<Age>20</Age>
<Address>
<City>Phoenix</City>
<State>Arizona</State>
<Country>USA</Country>
</Address>
<Designation>Technology Consultant</Designation>
<Salary>120000</Salary>
</Employee>

References