Skip to content

Commit

Permalink
Added [text()] syntax to retrieve all elements with non empty text
Browse files Browse the repository at this point in the history
  • Loading branch information
npiganeau authored and beevik committed Aug 9, 2017
1 parent 0974633 commit 49a60cf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
18 changes: 16 additions & 2 deletions path.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ only the following limited syntax is supported:
[tag] Selects all elements with a child element named tag
[tag='val'] Selects all elements with a child element named tag
and text matching val
[text()] Selects all elements with non empty text
[text()='val'] Selects all elements whose text matches val
Examples:
Expand Down Expand Up @@ -278,10 +279,12 @@ func (c *compiler) parseFilter(path string) filter {
}
}

// Filter contains [@attr], [N] or [tag]
// Filter contains [@attr], [N], [tag] or [text()]
switch {
case path[0] == '@':
return newFilterAttr(path[1:])
case strings.HasPrefix(path, "text()"):
return newFilterTextAll()
case isInteger(path):
pos, _ := strconv.Atoi(path)
switch {
Expand Down Expand Up @@ -432,14 +435,25 @@ func (f *filterAttrVal) apply(p *pather) {
// text equal to the specified value.
type filterTextVal struct {
val string
all bool
}

func newFilterTextVal(value string) *filterTextVal {
return &filterTextVal{value}
return &filterTextVal{val: value}
}

func newFilterTextAll() *filterTextVal {
return &filterTextVal{all: true}
}

func (f *filterTextVal) apply(p *pather) {
for _, c := range p.candidates {
if f.all {
if c.Text() != "" {
p.scratch = append(p.scratch, c)
}
continue
}
if c.Text() == f.val {
p.scratch = append(p.scratch, c)
}
Expand Down
6 changes: 6 additions & 0 deletions path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,16 @@ var testXML = `
<author>Giada De Laurentiis</author>
<year>2005</year>
<p:price>30.00</p:price>
<editor>Clarkson Potter</editor>
</book>
<book category="CHILDREN">
<title lang="en" sku="150">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<p:price>29.99</p:price>
<editor></editor>
<editor/>
</book>
<book category="WEB">
Expand All @@ -35,6 +38,8 @@ var testXML = `
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<p:price>49.99</p:price>
<editor>
</editor>
</book>
<!-- Final book -->
Expand Down Expand Up @@ -95,6 +100,7 @@ var tests = []test{
{"//book[price='29.99']/title", "Harry Potter"},
{"//book/price[text()='29.99']", "29.99"},
{"//book/author[text()='Kurt Cagle']", "Kurt Cagle"},
{"//book/editor[text()]", []string{"Clarkson Potter", "\n\t\t"}},

// attribute queries
{"./bookstore/book[@category='WEB']/title", []string{"XQuery Kick Start", "Learning XML"}},
Expand Down

0 comments on commit 49a60cf

Please # to comment.