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.

GoData Integrity

Code

gosnippet
42 lines
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

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.