sofr
sofr

Reputation: 5607

How to count specific nodes in xml hierachy depends on condition in XSL

I'm writing a stylesheet in xsl (version 2.0) I want to know how could I count all nodes with a specific name although they're not siblings for example in the following xml I want to count the numbers of Products from type -Milk but from all shops. I want to know if there's a way to use the count function and not struggling with Recursion. result should be 4 for this example

<Shops><Shop>
<Product>
    <Name>yogurt</Name>
    <type>Milk</type>
</Product>
<Product>
    <Name>cheese</Name>
    <type>Milk</type>
</Product>
<Product>
    <Name>bread</Name>
    <type>Bakery</type>
</Product> </Shop> <Shop>
<Product>
    <Name>yellow cheese</Name>
    <type>Milk</type>
</Product>
<Product>
    <Name>chocolate milk</Name>
    <type>Milk</type>
</Product>
<Product>
    <Name>bagel</Name>
    <type>Bakery</type>
</Product>
<Product>
    <Name>candy</Name>
    <type>Sweets</type>
</Product>  </Shop></Shops>

Upvotes: 0

Views: 5459

Answers (2)

Tomalak
Tomalak

Reputation: 338376

This avoids the slow "//" operator.

count(/Shops/Shop/Product[type = 'Milk'])

Upvotes: 4

AakashM
AakashM

Reputation: 63378

count(//Product[type='Milk'])

// finds all matching nodes anywhere in the document.

Upvotes: 2

Related Questions