Jon Harper
Jon Harper

Reputation: 105

How to do this XPath query?

I'm stuck with XPath query that I'm trying to do. I want to count all fish during certain moon. For full moon, query should return 2(there are 2 fish during that moon) My current query is this: count(//fish[//moon="full"]) . What's wrong here? It counts all fish instead of only 2.

XML is as follows:

<winterfishing>
<week number = "3">
   <moon>full</moon>
   <catch>
      <fish>
         <species>bass</species>
      </fish>
      <fish>
         <species>pike perch</species>
      </fish>
   </catch>
   <moon>
</week>
<week number = "4">
   <moon>half</moon>
   <catch>
      <fish>
         <species>perch</species>
      </fish>
   </catch>
   <moon>
</week>
</winterfishing>

Upvotes: 0

Views: 179

Answers (3)

Michael Kay
Michael Kay

Reputation: 163595

Basically, you've used // without understanding what it means. moon selects elements named moon that are children of the context node. //moon selects elments named moon anywhere in the current document.

Don't try to get XPath expressions right by trial and error, you will be in for many bad surprises. It's very tempting to think that XPath is such a small language that you can pick it up "by ear", but there are many unexpected quirks and it's much better to spend a couple of hours reading the spec and understanding the concepts before you start coding.

Upvotes: 0

Nero
Nero

Reputation: 43

When removing the orphaned, not-well forming, tags <moon>, then working queries are:

count(//week[moon="full"]/catch/fish) -> 2.0
count(//week[moon="half"]/catch/fish) -> 1.0

Upvotes: 0

Yitzhak Khabinsky
Yitzhak Khabinsky

Reputation: 22301

Your XML is not well-formed. So I had to fix it first.

XML

<winterfishing>
    <week number="3">
        <moon>full</moon>
        <catch>
            <fish>
                <species>bass</species>
            </fish>
            <fish>
                <species>pike perch</species>
            </fish>
        </catch>
        <!--<moon>-->
    </week>
    <week number="4">
        <moon>half</moon>
        <catch>
            <fish>
                <species>perch</species>
            </fish>
        </catch>
        <!--<moon>-->
    </week>
</winterfishing>

XPath

count(/winterfishing/week[moon="full"]/catch/fish)

Upvotes: 1

Related Questions