how to convert json to xml in golang?

Hi 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.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows


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 👍.

Follow me on Twitter