From bf1cb664f327e00797316c10607789fd062ba6f5 Mon Sep 17 00:00:00 2001 From: Brett Vickers Date: Fri, 17 Jan 2025 15:44:32 -0800 Subject: [PATCH] Element.Create returns the created element --- etree.go | 8 +++++--- etree_test.go | 5 +++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/etree.go b/etree.go index 8692675..3f087f7 100644 --- a/etree.go +++ b/etree.go @@ -773,15 +773,17 @@ type CreateContinuation func(e *Element) // This method of creating elements is useful when building nested XML // document from code. For example: // -// doc.Create("organization", func(e *Element) { +// org := doc.Create("organization", func(e *Element) { // e.Create("person", func(e *Element) { // e.CreateAttr("name", "Mary") // e.CreateAttr("age", "30") // e.CreateAttr("hair", "brown") // }) // }) -func (e *Element) Create(tag string, f CreateContinuation) { - f(e.CreateElement(tag)) +func (e *Element) Create(tag string, f CreateContinuation) *Element { + child := e.CreateElement(tag) + f(child) + return child } // AddChild adds the token 't' as the last child of the element. If token 't' diff --git a/etree_test.go b/etree_test.go index b4e062f..a3eaac1 100644 --- a/etree_test.go +++ b/etree_test.go @@ -1632,7 +1632,7 @@ func TestSiblingElement(t *testing.T) { func TestContinuations(t *testing.T) { doc := NewDocument() - doc.Create("root", func(e *Element) { + root := doc.Create("root", func(e *Element) { e.Create("child1", func(e *Element) { e.Create("grandchild1", func(e *Element) { e.CreateAttr("attr1", "1") @@ -1654,9 +1654,10 @@ func TestContinuations(t *testing.T) { }) }) }) - doc.IndentTabs() + checkStrEq(t, root.Tag, "root") // Serialize the document to a string + doc.IndentTabs() s, err := doc.WriteToString() if err != nil { t.Error("etree: failed to serialize document")