xml.Decoder Walks Tokens One At A Time

Stream XML incrementally with xml.Decoder.Token: start elements, character data, and end elements arrive as you ask, without loading the whole tree.

GoData Fetching

Code

gosnippet
35 lines
package main

import (
	"encoding/xml"
	"fmt"
	"strings"
)

const feed = `<?xml version="1.0"?>
<orders>
	<order id="1001">coffee</order>
	<order id="1002">tea</order>
</orders>`

func main() {
	dec := xml.NewDecoder(strings.NewReader(feed))

	// Token 按需推进:StartElement / CharData / EndElement 逐个到达
	for {
		tok, err := dec.Token()
		if err != nil {
			break // io.EOF 表示读完,其他 err 是解析错误
		}
		switch t := tok.(type) {
		case xml.StartElement:
			fmt.Println("start:", t.Name.Local)
		case xml.CharData:
			if text := strings.TrimSpace(string(t)); text != "" {
				fmt.Println("text:", text)
			}
		case xml.EndElement:
			fmt.Println("end:", t.Name.Local)
		}
	}
}

The shape of the program

The short version: the work belongs to the function main, doing all the work.

The file repeats itself only inside for. Nothing falls through silently — 1 checkpoint test err != nil on the way through.

What to watch for

  • The runtime is the only prerequisite — no packages, no install.

Applying it

The entry signature reads: func main()

Labeled lines come out — start:, text:, end: — when the file runs.

Statements that matter

if err != nil {
	break // io.EOF 表示读完,其他 err 是解析错误
}

Interactive Tools for This Topic

FAQ

What does xml.Decoder Walks Tokens One At A Time print when run?
Invoke the file as-is — the `start:`, `text:`, `end:` prefixes identify which step printed each line.