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
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go