type Person struct { Name string `xml:"name"` Age int `xml:"age"` Address string `xml:"address"` } func main() { xmlData := `` // create a new Decoder from an io.Reader decoder := xml.NewDecoder(strings.NewReader(xmlData)) var person Person // use the decoder to parse the XML data into the Person struct err := decoder.Decode(&person) if err != nil { log.Fatal(err) } fmt.Printf("Name: %s, Age: %d, Address: %s\n", person.Name, person.Age, person.Address) } John 30 123 Main St.
type Artist struct { Name string `xml:"name"` } type Response struct { Artists []Artist `xml:"artist"` } func main() { resp, err := http.Get("http://example.com/artists.xml") if err != nil { log.Fatal(err) } defer resp.Body.Close() var response Response // create a new Decoder from the HTTP response Body decoder := xml.NewDecoder(resp.Body) // use the decoder to parse the XML data into the Response struct err = decoder.Decode(&response) if err != nil { log.Fatal(err) } for i, artist := range response.Artists { fmt.Printf("%d. %s\n", i, artist.Name) } }In this example, we define a more complex `Response` struct with a slice of `Artist` struct instances. We then make an HTTP GET request to a server that responds with an XML document containing a list of artists, and use the `xml.Decoder` to parse the response into our `Response` struct. Finally, we loop over the `Artists` slice and print each artist's name. Overall, the `encoding/xml` package offers a flexible and easy-to-use API for working with XML data in Go, and is a convenient package when working with web services and other systems that exchange XML data.