Sling Academy
Home/Golang/Serializing and Deserializing Maps with XML in Go

Serializing and Deserializing Maps with XML in Go

Last updated: November 24, 2024

In the Go programming language, working with maps and XML is a common requirement, especially when it comes to data interchange between systems. Serialization refers to the process of converting objects or data structures into a format that can be easily stored or transmitted, while deserialization is the reverse process. In this article, we will explore how to serialize and deserialize maps with XML in Go.

1. Getting Started: Basic Serialization

First, we'll start with the basic serialization of a map to XML. Go's standard library provides a convenient package called encoding/xml.


package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

type Person struct {
    Name  string `xml:"name"`
    Email string `xml:"email"`
}

type People struct {
    XMLName xml.Name `xml:"people"`
    Persons []Person `xml:"person"`
}

func main() {
    people := People{
        Persons: []Person{
            {Name: "John Doe", Email: "[email protected]"},
            {Name: "Jane Smith", Email: "[email protected]"},
        },
    }

    enc := xml.NewEncoder(os.Stdout)
    enc.Indent("", "  ")

    if err := enc.Encode(people); err != nil {
        fmt.Println("Error encoding XML:", err)
        return
    }
}

2. Intermediate: Deserializing XML into a Map

The next step involves deserializing XML back into a map. We need to decode the XML structure into our defined structs.


package main

import (
    "encoding/xml"
    "fmt"
    "strings"
)

type Person struct {
    Name  string `xml:"name"`
    Email string `xml:"email"`
}

type People struct {
    XMLName xml.Name `xml:"people"`
    Persons []Person `xml:"person"`
}

func main() {
    data := `<people>
      <person>
        <name>John Doe</name>
        <email>[email protected]</email>
      </person>
      <person>
        <name>Jane Smith</name>
        <email>[email protected]</email>
      </person>
    </people>`

    var people People
    if err := xml.NewDecoder(strings.NewReader(data)).Decode(&people); err != nil {
        fmt.Println("Error decoding XML:", err)
        return
    }

    for _, p := range people.Persons {
        fmt.Printf("Name: %s, Email: %s\n", p.Name, p.Email)
    }
}

3. Advanced: Serializing and Deserializing Complex Maps

In some cases, maps are more complex and nested. Here we demonstrate handling complex XML mappings using Go by representing them as nested structs.


package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

type Address struct {
    Street string `xml:"street"`
    City   string `xml:"city"`
}

type ComplexPerson struct {
    Name    string  `xml:"name"`
    Email   string  `xml:"email"`
    Address Address `xml:"address"`
}

type People struct {
    XMLName xml.Name      `xml:"people"`
    Persons []ComplexPerson `xml:"person"`
}

func main() {
    people := People{
        Persons: []ComplexPerson{
            {
                Name:  "John Doe",
                Email: "[email protected]",
                Address: Address{Street: "123 Elm St", City: "Somewhere"},
            },
            {
                Name:  "Jane Smith",
                Email: "[email protected]",
                Address: Address{Street: "456 Oak St", City: "Anywhere"},
            },
        },
    }

    file, err := os.Create("people.xml")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    enc := xml.NewEncoder(file)
    enc.Indent("", "  ")

    if err := enc.Encode(people); err != nil {
        fmt.Println("Error encoding XML:", err)
    }

    fmt.Println("XML serialization complete, view 'people.xml' file.")
}

The file people.xml will contain the serialized XML data of complex maps.

Next Article: Maps in Configuration Management: Practical Examples in Go

Previous Article: Using Maps to Implement Simple In-Memory Databases in Go

Series: Working with Maps in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant