Go by Example: XML

Go provides built-in support for encoding and decoding XML data. XML (eXtensible Markup Language) is a widely-used data interchange format that is human-readable and easy to generate and parse.

Here’s a basic example that demonstrates how to encode a Go value into XML and then decode it back into a Go value:

package main

import (
	"encoding/xml"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "John Doe", Age: 30}

	// Encode p into XML
	b, err := xml.Marshal(p)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))

	// Decode XML into p2
	var p2 Person
	err = xml.Unmarshal(b, &p2)
	if err != nil {
		panic(err)
	}
	fmt.Println(p2)
}

In this example, a type Person is defined with two fields, Name and Age. A value of type Person is created and stored in the p variable.

The xml.Marshal function is called to encode p into an XML-encoded byte slice, which is stored in the b variable. The xml.Unmarshal function is then called to decode b into a value of type Person, which is stored in the p2 variable.

If the encoding and decoding operations are successful, the output will be:

<Person><Name>John Doe</Name><Age>30</Age></Person>
{John Doe 30}

Note that in this example, the Go value is being encoded into a byte slice and then decoded back into a Go value. However, XML encoding and decoding can also be performed directly with io primitives, such as os.File, bytes.Buffer, and net.Conn, for example. The encoding/xml package provides a rich set of options and functions for working with XML data in Go.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *