File tree 2 files changed +38
-0
lines changed
2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -1001,6 +1001,25 @@ func (e *Element) FindElementsPath(path Path) []*Element {
1001
1001
return p .traverse (e , path )
1002
1002
}
1003
1003
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
+
1004
1023
// GetPath returns the absolute path of the element. The absolute path is the
1005
1024
// full path from the document's root.
1006
1025
func (e * Element ) GetPath () string {
Original file line number Diff line number Diff line change @@ -1505,3 +1505,22 @@ func TestPreserveDuplicateAttrs(t *testing.T) {
1505
1505
checkAttr (e , 0 , "attr" , "test2" )
1506
1506
})
1507
1507
}
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
+ }
You can’t perform that action at this time.
0 commit comments