how to convert json to xml in golang?
September 05, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To convert json to xml in golang, use xml.MarshalIndent()
method, it will convert json to xml. You have to only pass your json in xml.MarshalIndent()
method.
Related Tutorials
Today, I will show you how do I convert a json to xml in golang, as above mentioned I’m going to use xml.MarshalIndent()
method.
To use the xml.MarshalIndent()
method, we have first import "encoding/xml"
package, then we have to create json variable which we will use to convert it in xml.
Let’s start our Golang convert json to xml example
main.go
package main
import (
"fmt"
"encoding/xml"
)
type Product struct {
ID uint64
Name string
SKU string
Cat Category
}
type Category struct {
ID uint64
Name string
}
func main() {
p := Product{ID: 42, Name: "Tea Pot", SKU: "TP12", Cat: Category{ID: 2, Name: "Tea"}}
bI, err := xml.MarshalIndent(p, "", " ")
if err != nil {
panic(err)
}
xmlWithHeader := xml.Header + string(bI)
fmt.Println(xmlWithHeader)
}
In the above example, we have converted the json value to a xml and printed in golang console. let’s check the output.
Output
<?xml version="1.0" encoding="UTF-8"?>
<Product>
<ID>42</ID>
<Name>Tea Pot</Name>
<SKU>TP12</SKU>
<Cat>
<ID>2</ID>
<Name>Tea</Name>
</Cat>
</Product>
I hope it helps you, All the best 👍.