Mugen
Mugen

Reputation: 9095

XPath: Collecting while aggregating issue

I have an XML file with the following structure:

<person height="170"/>
<person height="155"/>
<person height="192"/>
...
<tree height="100"/>
<tree height="300"/>
<tree height="120"/>

I need to return all the persons which have at least 3 trees with height that is in the range of the person's height +- 10.

For example, if a person has height of 155, the person would be returned iff there exists at least 3 trees with heights in the range of 145 to 165.

I tried to implement it and got as far as:

//person[count(//tree[@height >>>>>>is in range 10 to person's height<<<<<]) >= 3]

I'm stuck implementing the inner part. I tried using "current" and "self" but I don't seem to be using them right.

Upvotes: 1

Views: 46

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122394

This is one place where you can use the for $me in . idiom:

//person[count(for $me in . return //tree[
    @height <= ($me/@height + 10) and @height >= ($me/@height - 10)]) >= 3]

Here I'm using a single-iteration for expression to capture the current person (the . of the first-level predicate) so I can refer to it within the second-level predicate (where . is the tree).

Upvotes: 2

Related Questions