Skip to content

Commit

Permalink
add attribute sort support.
Browse files Browse the repository at this point in the history
The Element SortAttrs lexicographically sorts an element's attributes
by key.
  • Loading branch information
beevik committed Jun 9, 2018
1 parent 9d7e8fe commit 90dafc1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
24 changes: 24 additions & 0 deletions etree.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"errors"
"io"
"os"
"sort"
"strings"
)

Expand Down Expand Up @@ -781,6 +782,29 @@ func (e *Element) RemoveAttr(key string) *Attr {
return nil
}

// SortAttrs sorts the element's attributes lexicographically by key.
func (e *Element) SortAttrs() {
sort.Sort(byAttr(e.Attr))
}

type byAttr []Attr

func (a byAttr) Len() int {
return len(a)
}

func (a byAttr) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}

func (a byAttr) Less(i, j int) bool {
sp := strings.Compare(a[i].Space, a[j].Space)
if sp == 0 {
return strings.Compare(a[i].Key, a[j].Key) < 0
}
return sp < 0
}

var xmlReplacerNormal = strings.NewReplacer(
"&", "&amp;",
"<", "&lt;",
Expand Down
14 changes: 14 additions & 0 deletions etree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -485,3 +485,17 @@ func TestSetRoot(t *testing.T) {
s5, _ := doc.WriteToString()
checkEq(t, s5, expected5)
}

func TestSortAttrs(t *testing.T) {
testdoc := `<el foo='5' Foo='2' aaa='4' สวัสดี='7' AAA='1' a01='3' z='6' a:ZZZ='9' a:AAA='8'/>`
doc := NewDocument()
err := doc.ReadFromString(testdoc)
if err != nil {
t.Fatal("etree ReadFromString: " + err.Error())
}

doc.Root().SortAttrs()
doc.Indent(2)
out, _ := doc.WriteToString()
checkEq(t, out, `<el AAA="1" Foo="2" a01="3" aaa="4" foo="5" z="6" สวัสดี="7" a:AAA="8" a:ZZZ="9"/>`+"\n")
}

0 comments on commit 90dafc1

Please sign in to comment.