From f9721ff411f6e3e38b081565f846c5e7b2852c5d Mon Sep 17 00:00:00 2001 From: Brett Vickers Date: Mon, 5 Jun 2023 11:26:35 -0700 Subject: [PATCH] Add Element.ReindexChildren function 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. --- etree.go | 9 +++++++++ etree_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/etree.go b/etree.go index 83df8b2..1d1e084 100644 --- a/etree.go +++ b/etree.go @@ -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 { diff --git a/etree_test.go b/etree_test.go index 9f1df3e..847d813 100644 --- a/etree_test.go +++ b/etree_test.go @@ -8,6 +8,7 @@ import ( "bytes" "encoding/xml" "io" + "math/rand" "strings" "testing" ) @@ -1358,3 +1359,38 @@ func TestTokenWriteTo(t *testing.T) { checkStrEq(t, buffer.String(), test.expected) } } + +func TestReindexChildren(t *testing.T) { + s := ` + + + + + +` + 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") + } + } +}