Skip to content

Commit

Permalink
Add Element.ReindexChildren function
Browse files Browse the repository at this point in the history
ReindexChildren recalculates the index values of the element's child
tokens. This is necessary only if you have manually manipulated the
element's `Child` array.
  • Loading branch information
beevik committed Jun 5, 2023
1 parent ef16dc1 commit f9721ff
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions etree.go
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,15 @@ func (e *Element) name() string {
return e.Tag
}

// ReindexChildren recalculates the index values of the element's child
// tokens. This is necessary only if you have manually manipulated the
// element's `Child` array.
func (e *Element) ReindexChildren() {
for i := 0; i < len(e.Child); i++ {
e.Child[i].setIndex(i)
}
}

// Text returns all character data immediately following the element's opening
// tag.
func (e *Element) Text() string {
Expand Down
36 changes: 36 additions & 0 deletions etree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"bytes"
"encoding/xml"
"io"
"math/rand"
"strings"
"testing"
)
Expand Down Expand Up @@ -1358,3 +1359,38 @@ func TestTokenWriteTo(t *testing.T) {
checkStrEq(t, buffer.String(), test.expected)
}
}

func TestReindexChildren(t *testing.T) {
s := `<root>
<child1/>
<child2/>
<child3/>
<child4/>
<child5/>
</root>`
doc := newDocumentFromString(t, s)
doc.Unindent()

root := doc.Root()
if root == nil || root.Tag != "root" || len(root.Child) != 5 {
t.Error("etree: expected root element not found")
}

for i := 0; i < len(root.Child); i++ {
if root.Child[i].Index() != i {
t.Error("etree: incorrect child index found in root element child")
}
}

rand.Shuffle(len(root.Child), func(i, j int) {
root.Child[i], root.Child[j] = root.Child[j], root.Child[i]
})

root.ReindexChildren()

for i := 0; i < len(root.Child); i++ {
if root.Child[i].Index() != i {
t.Error("etree: incorrect child index found in root element child")
}
}
}

0 comments on commit f9721ff

Please sign in to comment.