user1891340
user1891340

Reputation: 29

Use of count in Xpath expressions

if I have an XML like this: (just to do an example)

<restaurant>
    <tables>
            <table id=1 />
            <table id=2 />
            <table id=3 />
    </tables>

And I have to count the number of tables, the correct Xpath expression is:

restaurant/tables/count(table)

or

count(restaurant/tables/table)

?

Thank you

Upvotes: 2

Views: 15633

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243579

restaurant/tables/count(table)

This expression is only legal in XPath 2.0. It produces a sequence of numbers and this sequence may have length greater than one if the XML document has more than one restorant or restorant/tables elements.

count(restaurant/tables/table)

This expression is valid both in XPath 1.0 and XPath 2.0. It produces a single number.

So, in general, the two expressions are different, only the second is legal in XPath 1.0 and in XPath 2.0 these expressions may produce different results, depending on the XML document against which they are evaluated.

However on the specified XML document, these two expressions (when evaluated in XPath 2.0) produce the same result:

3

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272407

Check out this Microsoft XPath count() tutorial.

count(/restaurant/tables/table)

will count the table elements in the above path.

Upvotes: 4

Related Questions