How to encode and decode data in XML format in Go using the encoding/xml package?

To encode and decode data in XML format in Go using the encoding/xml package, you can follow the steps mentioned below:

  1. Import the "encoding/xml" package into your code:

    import "encoding/xml"
  2. Define the structure of your XML data using Go struct tags. Specify the XML element names using the xml:"" tag:

    type MyData struct { XMLName xml.Name `xml:"root"` Value string `xml:"value"` }
  3. Encoding - Convert Go data to XML format:

    • Create an instance of your data structure to encode:

      data := MyData{ Value: "Hello, World!", }
    • Encode the data using the xml.Marshal() function:

      xmlData, err := xml.Marshal(data) if err != nil { // handle error }
    • Convert the XML byte slice to string and print:

      xmlString := string(xmlData) fmt.Println(xmlString)
  4. Decoding - Convert XML data to Go format:

    • Create a variable of your data structure to decode into:

      var decodedData MyData
    • Convert the XML string to a byte slice:

      xmlData := []byte(xmlString)
    • Decode the XML data into the Go struct using the xml.Unmarshal() function:

      err = xml.Unmarshal(xmlData, &decodedData) if err != nil { // handle error }
    • Access the decoded values:

      fmt.Println(decodedData.Value)

That's it! You have now encoded your Go data structure into XML format and decoded XML data into a Go structure using the encoding/xml package in Go.