-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarshal.go
211 lines (190 loc) · 5.32 KB
/
marshal.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package libxml
import (
"errors"
"fmt"
"reflect"
"strconv"
"github.com/jbowtie/gokogiri/xml"
)
const nsCleanParseOption = xml.XML_PARSE_RECOVER |
xml.XML_PARSE_NONET |
xml.XML_PARSE_NOERROR |
xml.XML_PARSE_NOWARNING |
xml.XML_PARSE_NSCLEAN
// ErrNoRoot is thrown when no root XMLName field is found
var ErrNoRoot = errors.New("XMLName not defined on root element")
// Marshal returns the XML encoding of v.¨
//
// See https://golang.org/pkg/encoding/xml/#Marshal for more information.
func Marshal(v interface{}) (string, error) {
// Attempt to resolve struct/structpointer
if v == nil {
return "", ErrInvalidStructPtr
}
s := reflect.ValueOf(v)
if s.Type().Kind() == reflect.Ptr {
s = s.Elem()
}
if s.NumField() == 0 {
return "", nil
}
t := s.Type()
// Create document
doc := xml.CreateEmptyDocument([]byte("UTF-8"), []byte("UTF-8"))
// Get root node tag name and namespace
xmlNameField, ok := t.FieldByName("XMLName")
if !ok {
return "", ErrNoRoot
}
xmlNameTag := parseXMLTag(xmlNameField.Tag)
// Create root node
root := doc.CreateElementNode(xmlNameTag.tagName)
if xmlNameTag.namespace != "" {
root.SetNamespace("", xmlNameTag.namespace)
}
doc.AddChild(root)
// Fill values
err := fillNodeFromStruct(doc, root, s)
if err != nil {
return "", err
}
// Clean up namespaces
dirtyDoc, _ := doc.SerializeWithFormat(xml.XML_SAVE_AS_XML, []byte("UTF-8"), nil)
cleanDoc, err := xml.Parse(dirtyDoc, []byte("UTF-8"), []byte{}, nsCleanParseOption, []byte("UTF-8"))
if err != nil {
return "", err
}
// Serialize and return output
out, _ := cleanDoc.SerializeWithFormat(xml.XML_SAVE_AS_XML, []byte("UTF-8"), nil)
return string(out), nil
}
func getStringFromVal(t reflect.Type, s reflect.Value) (string, error) {
switch t.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(s.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(s.Uint(), 10), nil
case reflect.Float32:
return strconv.FormatFloat(s.Float(), 'f', -1, 32), nil
case reflect.Float64:
return strconv.FormatFloat(s.Float(), 'f', -1, 64), nil
case reflect.String:
return s.String(), nil
case reflect.Bool:
return strconv.FormatBool(s.Bool()), nil
}
return "", fmt.Errorf("Type %s (%s) not implemented", t.Kind().String(), t.String())
}
func setContentFromStructField(doc *xml.XmlDocument, t reflect.Type, s reflect.Value, n xml.Node, cdata bool) error {
switch t.Kind() {
case reflect.Ptr:
return setContentFromStructField(doc, t.Elem(), s.Elem(), n, false)
case reflect.Interface:
if reflect.DeepEqual(s.Interface(), reflect.Zero(t).Interface()) {
return nil
}
return setContentFromStructField(doc, s.Elem().Type(), s.Elem(), n, false)
case reflect.Struct:
return fillNodeFromStruct(doc, n, s)
default:
str, err := getStringFromVal(t, s)
if err != nil {
return err
}
if cdata {
cdataNode := doc.CreateCDataNode(str)
n.AddChild(cdataNode)
} else {
n.SetContent(str)
}
}
return nil
}
func setAttrFromStructField(t reflect.Type, s reflect.Value, n xml.Node, attrName string) error {
switch t.Kind() {
case reflect.Ptr:
return setAttrFromStructField(t.Elem(), s.Elem(), n, attrName)
default:
str, err := getStringFromVal(t, s)
if err != nil {
return err
}
n.SetAttr(attrName, str)
}
return nil
}
func fillNodeFromStruct(doc *xml.XmlDocument, n xml.Node, s reflect.Value) error {
t := s.Type()
for i := 0; i < s.NumField(); i++ {
tField := t.Field(i)
if tField.Name == "XMLName" {
continue
}
sField := s.Field(i)
// Get XML tag name and namespace from struct definition
tagNS := ""
fullTagName := ""
isAttr := false
isCDATA := false
if xmlTag := parseXMLTag(tField.Tag); xmlTag != nil {
if reflect.DeepEqual(sField.Interface(), reflect.Zero(tField.Type).Interface()) && xmlTag.flagOmitEmpty {
continue
} else if xmlTag.flagAttribute {
isAttr = true
} else if xmlTag.flagChardata {
err := setContentFromStructField(doc, tField.Type, sField, n, false)
if err != nil {
return err
}
continue
} else if xmlTag.flagCDATA {
isCDATA = true
}
fullTagName = xmlTag.tagName
tagNS = xmlTag.namespace
} else {
// Fall back to field name if tag name is empty
fullTagName = tField.Name
}
// Fall back to type name if tag name is empty
if fullTagName == "" {
if tField.Type.Kind() == reflect.Ptr {
fullTagName = sField.Elem().Type().String()
} else {
fullTagName = tField.Type.String()
}
}
prefix, tagName := splitTagPrefix(fullTagName)
if isAttr {
err := setAttrFromStructField(tField.Type, sField, n, tagName)
if err != nil {
return err
}
} else {
if tField.Type.Kind() == reflect.Slice {
for i := 0; i < sField.Len(); i++ {
node := doc.CreateElementNode(tagName)
if tagNS != "" {
node.SetNamespace(prefix, tagNS)
}
err := setContentFromStructField(doc, sField.Type().Elem(), sField.Index(i), node, false)
if err != nil {
return err
}
n.AddChild(node)
}
} else {
node := doc.CreateElementNode(tagName)
if tagNS != "" {
node.SetNamespace(prefix, tagNS)
}
err := setContentFromStructField(doc, tField.Type, sField, node, isCDATA)
if err != nil {
return err
}
n.AddChild(node)
}
}
}
return nil
}