-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
80 lines (66 loc) · 1.22 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"os"
"strings"
"golang.org/x/text/encoding/htmlindex"
"golang.org/x/text/transform"
)
type (
Root struct {
Items []string `xml:"-"`
}
)
func main() {
var (
r Root
rd, err = os.Open("./test.xml")
)
if err != nil {
panic(err)
}
xr := xml.NewDecoder(rd)
buf := new(bytes.Buffer)
var start, end, offset int64
xr.CharsetReader = func(label string, input io.Reader) (io.Reader, error) {
charset, err := htmlindex.Get(label)
if err != nil {
return nil, err
}
offset = xr.InputOffset()
decoder := transform.NewReader(input, charset.NewDecoder())
return io.TeeReader(decoder, buf), nil
}
loop:
for {
tok, err := xr.RawToken()
if err != nil {
if err == io.EOF {
break loop
}
panic(err)
}
switch t := tok.(type) {
case xml.StartElement:
switch t.Name.Local {
case "r":
start = xr.InputOffset()
}
case xml.EndElement:
switch t.Name.Local {
case "a":
end = xr.InputOffset()
r.Items = append(r.Items, strings.TrimSpace(buf.String()[start-offset:end-offset]))
start = end
case "r":
break loop
}
}
}
for i := range r.Items {
fmt.Printf("%d: %s\n", i+1, r.Items[i])
}
}