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.

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
- https://golang.org/src/encoding/xml/example_test.go
- https://en.wikipedia.org/wiki/Marshalling_(computer_science)
- https://idineshkrishnan.com/how-to-convert-object-to-xml-using-jaxb/
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet