-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
sort.go
48 lines (38 loc) · 1019 Bytes
/
sort.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
package xml
import (
"bytes"
"encoding/xml"
"io"
"strings"
)
type xmlAttrSlice []xml.Attr
func (x xmlAttrSlice) Len() int {
return len(x)
}
func (x xmlAttrSlice) Less(i, j int) bool {
spaceI, spaceJ := x[i].Name.Space, x[j].Name.Space
localI, localJ := x[i].Name.Local, x[j].Name.Local
valueI, valueJ := x[i].Value, x[j].Value
spaceCmp := strings.Compare(spaceI, spaceJ)
localCmp := strings.Compare(localI, localJ)
valueCmp := strings.Compare(valueI, valueJ)
if spaceCmp == -1 || (spaceCmp == 0 && (localCmp == -1 || (localCmp == 0 && valueCmp == -1))) {
return true
}
return false
}
func (x xmlAttrSlice) Swap(i, j int) {
x[i], x[j] = x[j], x[i]
}
// SortXML sorts the reader's XML elements
func SortXML(r io.Reader, ignoreIndentation bool) (string, error) {
var buf bytes.Buffer
d := xml.NewDecoder(r)
root, err := ToStruct(d, nil, ignoreIndentation)
if err != nil {
return buf.String(), err
}
e := xml.NewEncoder(&buf)
err = StructToXML(e, root, true)
return buf.String(), err
}