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.

Related Tutorials

Golang JSON to string

Golang JSON to XML

Golang JSON to Map

Golang JSON to Struct

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

Try it Yourself

Premium Content

You can get all the below premium content directly in your mail when you subscribe us


Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts