Skip to content

Commit f4e0a85

Browse files
authored
Add element NotNil function (#130)
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.
1 parent d21e1ce commit f4e0a85

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

etree.go

+19
Original file line numberDiff line numberDiff line change
@@ -1001,6 +1001,25 @@ func (e *Element) FindElementsPath(path Path) []*Element {
10011001
return p.traverse(e, path)
10021002
}
10031003

1004+
// NotNil returns the receiver element if it isn't nil; otherwise, it returns
1005+
// an unparented element with an empty string tag. This function simplifies
1006+
// the task of writing code to ignore not-found results from element queries.
1007+
// For example, instead of writing this:
1008+
//
1009+
// if e := doc.SelectElement("enabled"); e != nil {
1010+
// e.SetText("true")
1011+
// }
1012+
//
1013+
// You could write this:
1014+
//
1015+
// doc.SelectElement("enabled").NotNil().SetText("true")
1016+
func (e *Element) NotNil() *Element {
1017+
if e == nil {
1018+
return NewElement("")
1019+
}
1020+
return e
1021+
}
1022+
10041023
// GetPath returns the absolute path of the element. The absolute path is the
10051024
// full path from the document's root.
10061025
func (e *Element) GetPath() string {

etree_test.go

+19
Original file line numberDiff line numberDiff line change
@@ -1505,3 +1505,22 @@ func TestPreserveDuplicateAttrs(t *testing.T) {
15051505
checkAttr(e, 0, "attr", "test2")
15061506
})
15071507
}
1508+
1509+
func TestNotNil(t *testing.T) {
1510+
s := `<enabled>true</enabled>`
1511+
1512+
doc := newDocumentFromString(t, s)
1513+
doc.SelectElement("enabled").NotNil().SetText("false")
1514+
doc.SelectElement("visible").NotNil().SetText("true")
1515+
1516+
want := `<enabled>false</enabled>`
1517+
got, err := doc.WriteToString()
1518+
if err != nil {
1519+
t.Fatal("etree: failed to write document to string")
1520+
}
1521+
if got != want {
1522+
t.Error("etree: unexpected NotNil result")
1523+
t.Error("wanted:\n" + want)
1524+
t.Error("got:\n" + got)
1525+
}
1526+
}

0 commit comments

Comments
 (0)