Skip to content

Commit

Permalink
feat: writer support sort attr
Browse files Browse the repository at this point in the history
  • Loading branch information
yywing committed Dec 27, 2024
1 parent 8965a48 commit 7dc34a2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
7 changes: 7 additions & 0 deletions etree.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ type WriteSettings struct {
//
// Deprecated: UseCRLF is deprecated. Use IndentSettings.UseCRLF instead.
UseCRLF bool

// SortAttrs to sort attr
SortAttrs bool
}

// dup creates a duplicate of the WriteSettings object.
Expand Down Expand Up @@ -1330,6 +1333,10 @@ func (e *Element) Index() int {
func (e *Element) WriteTo(w Writer, s *WriteSettings) {
w.WriteByte('<')
w.WriteString(e.FullTag())

if s.SortAttrs {
e.SortAttrs()
}
for _, a := range e.Attr {
w.WriteByte(' ')
a.WriteTo(w, s)
Expand Down
10 changes: 10 additions & 0 deletions etree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,16 @@ func TestSortAttrs(t *testing.T) {
checkStrEq(t, out, `<el AAA="1" Foo="2" a01="3" aaa="4" foo="5" z="6" สวัสดี="7" a:AAA="8" a:ZZZ="9"/>`+"\n")
}

func TestWriteSortAttrs(t *testing.T) {
doc := NewDocument()
doc.WriteSettings.SortAttrs = true
s := `<el foo='5' Foo='2' aaa='4' สวัสดี='7' AAA='1' a01='3' z='6' a:ZZZ='9' a:AAA='8'/>`
doc.ReadFromString(s)
doc.Indent(2)
out, _ := doc.WriteToString()
checkStrEq(t, out, `<el AAA="1" Foo="2" a01="3" aaa="4" foo="5" z="6" สวัสดี="7" a:AAA="8" a:ZZZ="9"/>`+"\n")
}

func TestCharsetReaderDefaultSetting(t *testing.T) {
// Test encodings where the default pass-through charset conversion
// should work for common single-byte character encodings.
Expand Down

0 comments on commit 7dc34a2

Please sign in to comment.