Skip to content

Commit

Permalink
Add element NotNil function (#130)
Browse files Browse the repository at this point in the history
NotNil returns the receiver element if it isn't nil; otherwise, it returns
an unparented element with an empty string tag. This function simplifies
the task of writing code to ignore not-found results from element queries.
  • Loading branch information
beevik authored Apr 28, 2024
1 parent d21e1ce commit f4e0a85
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions etree.go
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,25 @@ func (e *Element) FindElementsPath(path Path) []*Element {
return p.traverse(e, path)
}

// NotNil returns the receiver element if it isn't nil; otherwise, it returns
// an unparented element with an empty string tag. This function simplifies
// the task of writing code to ignore not-found results from element queries.
// For example, instead of writing this:
//
// if e := doc.SelectElement("enabled"); e != nil {
// e.SetText("true")
// }
//
// You could write this:
//
// doc.SelectElement("enabled").NotNil().SetText("true")
func (e *Element) NotNil() *Element {
if e == nil {
return NewElement("")
}
return e
}

// GetPath returns the absolute path of the element. The absolute path is the
// full path from the document's root.
func (e *Element) GetPath() string {
Expand Down
19 changes: 19 additions & 0 deletions etree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1505,3 +1505,22 @@ func TestPreserveDuplicateAttrs(t *testing.T) {
checkAttr(e, 0, "attr", "test2")
})
}

func TestNotNil(t *testing.T) {
s := `<enabled>true</enabled>`

doc := newDocumentFromString(t, s)
doc.SelectElement("enabled").NotNil().SetText("false")
doc.SelectElement("visible").NotNil().SetText("true")

want := `<enabled>false</enabled>`
got, err := doc.WriteToString()
if err != nil {
t.Fatal("etree: failed to write document to string")
}
if got != want {
t.Error("etree: unexpected NotNil result")
t.Error("wanted:\n" + want)
t.Error("got:\n" + got)
}
}

0 comments on commit f4e0a85

Please sign in to comment.