-
Notifications
You must be signed in to change notification settings - Fork 0
/
element.go
123 lines (107 loc) · 2.41 KB
/
element.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package xml
import (
"fmt"
"strings"
)
type Namespace struct {
Prefix string
URI string
}
// Element --------------------------------------------------------------------
type Element struct {
Name QName
Attributes []attribute
Namespaces map[string]string
Children []*Element
Parent *Element
Closed bool
Text string
}
func NewElement() *Element {
return &Element{
Namespaces: make(map[string]string),
}
}
func (el *Element) GetAttributeValue(name string) (string, bool) {
for _, attr := range el.Attributes {
if attr.name.Name == name {
return attr.value, true
}
}
return "", false
}
func (el *Element) GetAttributeKeys() []QName {
tmp := []QName{}
for _, attr := range el.Attributes {
tmp = append(tmp, attr.name)
}
return tmp
}
func (el *Element) HasParent(name string) bool {
if el.Parent.Name.Name == name {
return true
}
return false
}
func (el *Element) GetChildren(name string) []*Element {
tmp := []*Element{}
for _, c := range el.Children {
if c.Name.Name == name {
tmp = append(tmp, c)
}
}
return tmp
}
func (el *Element) GetNamespace(name QName) string {
ns, ok := el.Namespaces[name.Prefix]
if !ok {
ns, ok := el.Namespaces["$default"]
if !ok {
return ""
}
return ns
}
return ns
}
func (el *Element) ToYaml() string {
return el.toYaml(0)
}
// Internal -------------------------------------------------------------------
func (el *Element) toYaml(indent int) string {
indentStr, pref := strings.Repeat(" ", indent), ""
if el.Name.Prefix != "" {
pref = el.Name.Prefix + "-"
}
tmp := fmt.Sprintf("%s%s:\n", pref, el.Name.Name)
tmp += indentStr + " attributes:\n"
for _, attr := range el.Attributes {
pref = ""
if attr.name.Prefix != "" {
pref = attr.name.Prefix + "-"
}
tmp += fmt.Sprintf("%s - %s%s: %s\n",
indentStr, pref, attr.name.Name, attr.value)
}
tmp += indentStr + " children:\n"
for _, child := range el.Children {
tmp += indentStr + " - " + child.toYaml(indent+2)
}
return tmp
}
func (el *Element) addNamespaces() {
tmp := map[string]string{}
if el.Parent != nil {
for key, val := range el.Parent.Namespaces {
tmp[key] = val
}
}
for _, attr := range el.Attributes {
if strings.ToLower(attr.name.Prefix) == "xmlns" {
tmp[attr.name.Name] = attr.value
}
if attr.name.Prefix == "" && strings.ToLower(attr.name.Name) == "xmlns" {
tmp["$default"] = attr.value
}
}
el.Namespaces = tmp
}