-
Notifications
You must be signed in to change notification settings - Fork 176
/
Copy pathmain.go
81 lines (73 loc) · 1.52 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
81
// ex7.18 parses XML into a tree of nodes, using the token-based API of
// encoding/xml.
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"os"
)
type Node interface{} // CharData or *Element
type CharData string
type Element struct {
Type xml.Name
Attr []xml.Attr
Children []Node
}
func (n *Element) String() string {
b := &bytes.Buffer{}
visit(n, b, 0)
return b.String()
}
func visit(n Node, w io.Writer, depth int) {
switch n := n.(type) {
case *Element:
fmt.Fprintf(w, "%*s%s %s\n", depth*2, "", n.Type.Local, n.Attr)
for _, c := range n.Children {
visit(c, w, depth+1)
}
case CharData:
fmt.Fprintf(w, "%*s%q\n", depth*2, "", n)
default:
panic(fmt.Sprintf("got %T", n))
}
}
func parse(r io.Reader) (Node, error) {
dec := xml.NewDecoder(r)
var stack []*Element
var root Node
for {
tok, err := dec.Token()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
switch tok := tok.(type) {
case xml.StartElement:
el := &Element{tok.Name, tok.Attr, nil}
if len(stack) == 0 {
root = el
} else {
parent := stack[len(stack)-1]
parent.Children = append(parent.Children, el)
}
stack = append(stack, el) // push
case xml.EndElement:
stack = stack[:len(stack)-1] // pop
case xml.CharData:
parent := stack[len(stack)-1]
parent.Children = append(parent.Children, CharData(tok))
}
}
return root, nil
}
func main() {
node, err := parse(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
fmt.Println(node)
}