XML in Go

Go: XML

XML (Extensible Markup Language) is a markup language that is widely used for encoding data in a machine-readable format. Go provides built-in support for encoding and decoding XML data using the standard library package encoding/xml.

Encode a Go data structure to XM

To encode a Go data structure to XML, you can use the xml.Marshal() function, which takes a Go value and returns a byte slice containing its XML representation. For example:

    import (
        "encoding/xml"
        "fmt"
    )

    type Person struct {
        Name string
        Age int
    }

    func main() {
        person := Person{Name: "Alice", Age: 30}
        xmlBytes, err := xml.Marshal(person)
        if err != nil {
            panic(err)
        }
        fmt.Println(string(xmlBytes)) // Output: <Person><Name>Alice</Name><Age>30</Age></Person>
    }

Decode a Go data structure to XM

To decode XML data into a Go data structure, you can use the xml.Unmarshal() function, which takes a byte slice containing XML data and a pointer to a Go value, and sets the value to the decoded data. For example:

    func main() {
        xmlStr := `<Person><Name>Bob</Name><Age>25</Age></Person>`
        var person Person
        err := xml.Unmarshal([]byte(xmlStr), &person)
        if err != nil {
            panic(err)
        }
        fmt.Println(person.Name, person.Age) // Output: Bob 25
    }
  • Note that the field names in the Go struct must be exported (i.e. capitalized) in order to be encoded or decoded by the encoding/xml package. You can use struct tags to specify custom field names in the XML data. For example:
    type Person struct {
        Name string `xml:"name"`
        Age int `xml:"age"`
    }

    func main() {
        person := Person{Name: "Charlie", Age: 20}
        xmlBytes, err := xml.Marshal(person)
        if err != nil {
            panic(err)
        }
        fmt.Println(string(xmlBytes)) // Output: <Person><name>Charlie</name><age>20</age></Person>
    }

Previous Article