-
Notifications
You must be signed in to change notification settings - Fork 0
/
transformer.go
91 lines (71 loc) · 1.53 KB
/
transformer.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
package xmler
import (
"bytes"
"container/list"
"encoding/xml"
"io"
"io/ioutil"
"log"
"strings"
"text/template"
)
type Transformer struct {
elements Elements
}
func NewTransformer() Transformer {
return Transformer{
elements: NewElements(),
}
}
func (self *Transformer) Parse(filePath string) Elements {
data, err := ioutil.ReadFile(filePath)
if err != nil {
log.Fatalln(err)
}
d := xml.NewDecoder(bytes.NewReader(data))
var lastParent *list.Element
for {
t, err := d.Token()
if err == io.EOF {
break
}
if err != nil && err != io.EOF {
log.Fatalln(err)
}
switch token := t.(type) {
case xml.StartElement:
e := &Element{
Type: token.Name.Local,
}
for _, a := range token.Attr {
e.addAttr(a.Name.Local, a.Value)
}
if lastParent != nil {
e.Parent = lastParent.Value.(*Element)
}
lastParent = self.elements.PushBack(e)
case xml.EndElement:
lastParent = lastParent.Prev()
case xml.CharData:
// adds tag content from <tag>conent</tag> to element.Value
value := strings.TrimSpace(string(token[:]))
if value != "" {
e := self.elements.Back().Value.(*Element)
e.Value = value
}
}
}
return self.elements
}
func (self *Transformer) Transform(xmlFilePath, tplFilePath string) bytes.Buffer {
elements := self.Parse(xmlFilePath)
tpl, err := template.ParseFiles(tplFilePath)
if err != nil {
log.Fatalln(err)
}
var buf bytes.Buffer
if err := tpl.Execute(&buf, elements.Slice()); err != nil {
log.Fatalf("generating code: %v", err)
}
return buf
}