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.

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


package main
import (

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 {
    xmlWithHeader := xml.Header + string(bI)

In the above example, we have converted the json value to a xml and printed in golang console. let’s check the output.


<?xml version="1.0" encoding="UTF-8"?>
   <Name>Tea Pot</Name>

I hope it helps you, All the best 👍.

Follow me on Twitter