XML Marshal Unmarshal Round Trip
Round-trip a typed catalog through encoding/xml: struct tags turn fields into attributes and child elements, and Unmarshal reads them back into the same values.
Code
package main
import (
"encoding/xml"
"fmt"
)
// xml 标签:attr 写成属性,普通标签写成子元素
type Item struct {
Name string `xml:"name,attr"`
SKU string `xml:"sku,attr"`
Price float64 `xml:"price"`
Stock int `xml:"stock"`
}
type Catalog struct {
XMLName xml.Name `xml:"catalog"`
Items []Item `xml:"item"`
}
func main() {
source := Catalog{
Items: []Item{
{Name: "widget", SKU: "W-1", Price: 1.99, Stock: 42},
{Name: "gadget", SKU: "G-7", Price: 9.95, Stock: 0},
},
}
out, err := xml.MarshalIndent(source, "", " ")
if err != nil {
panic(err)
}
fmt.Println(xml.Header + string(out))
// Unmarshal 按标签落位:属性与子元素都回到字段里
var parsed Catalog
if err := xml.Unmarshal(out, &parsed); err != nil {
panic(err)
}
fmt.Printf("decoded %d items, first: %+v
", len(parsed.Items), parsed.Items[0])
}The execution narrative
Count the function main as the entire surface area of XML Marshal Unmarshal Round Trip.
Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.
Watch out for
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Key statements
if err != nil {
panic(err)
}
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- What is the error handling style?
- The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
- How do you run XML Marshal Unmarshal Round Trip?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.