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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.