-
Notifications
You must be signed in to change notification settings - Fork 22
/
xml.go
103 lines (85 loc) · 2.07 KB
/
xml.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package xml
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"strings"
. "github.com/kocircuit/kocircuit/lang/go/eval"
"github.com/kocircuit/kocircuit/lang/go/runtime"
)
func init() {
RegisterEvalGate(new(GoRenderElement))
RegisterEvalGate(new(GoTagElement))
RegisterEvalGate(new(GoDocTypeElement))
RegisterEvalGate(new(GoTextElement))
RegisterEvalGate(new(GoGroupElement))
}
// Elements: GoTagElement, GoDocTypeElement, GoTextElement, GoGroupElement
type Element interface {
WriteXML(io.Writer)
}
type GoTagElement struct {
Tag string `ko:"name=tag"`
Attrs []string `ko:"name=attrs"`
Children []Element `ko:"name=children"`
}
func (g *GoTagElement) Play(ctx *runtime.Context) Element {
return g
}
func (g *GoTagElement) WriteXML(w io.Writer) {
if len(g.Children) == 0 {
fmt.Fprintf(w, "<%s %s />", g.Tag, strings.Join(g.Attrs, " "))
} else {
fmt.Fprintf(w, "<%s %s>", g.Tag, strings.Join(g.Attrs, " "))
for i, child := range g.Children {
child.WriteXML(w)
if i+1 < len(g.Children) {
w.Write([]byte(" "))
}
}
fmt.Fprintf(w, "</%s>", g.Tag)
}
}
type GoDocTypeElement struct {
String_ string `ko:"name=string,monadic"`
}
func (g *GoDocTypeElement) Play(ctx *runtime.Context) Element {
return g
}
func (g *GoDocTypeElement) WriteXML(w io.Writer) {
fmt.Fprintf(w, "<!DOCTYPE %s>", g.String_)
}
type GoTextElement struct {
String_ string `ko:"name=string,monadic"`
}
func (g *GoTextElement) Play(ctx *runtime.Context) Element {
return g
}
func (g *GoTextElement) WriteXML(w io.Writer) {
xml.EscapeText(w, []byte(g.String_))
}
type GoGroupElement struct {
Elem []Element `ko:"name=elem,monadic"`
}
func (g *GoGroupElement) Play(ctx *runtime.Context) Element {
return g
}
func (g *GoGroupElement) WriteXML(w io.Writer) {
for i, e := range g.Elem {
e.WriteXML(w)
if i+1 < len(g.Elem) {
w.Write([]byte(" "))
}
}
}
type GoRenderElement struct {
Elem []Element `ko:"name=elem,monadic"`
}
func (g *GoRenderElement) Play(ctx *runtime.Context) string {
var w bytes.Buffer
for _, elem := range g.Elem {
elem.WriteXML(&w)
}
return w.String()
}