Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: writer support sort attr #144

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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