diff --git a/etree.go b/etree.go index 761bece..c3bb746 100644 --- a/etree.go +++ b/etree.go @@ -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 { diff --git a/etree_test.go b/etree_test.go index e501d7b..11c0eea 100644 --- a/etree_test.go +++ b/etree_test.go @@ -1505,3 +1505,22 @@ func TestPreserveDuplicateAttrs(t *testing.T) { checkAttr(e, 0, "attr", "test2") }) } + +func TestNotNil(t *testing.T) { + s := `true` + + doc := newDocumentFromString(t, s) + doc.SelectElement("enabled").NotNil().SetText("false") + doc.SelectElement("visible").NotNil().SetText("true") + + want := `false` + 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) + } +}