tags:

views:

289

answers:

2

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>
A: 

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

// finds all matching nodes anywhere in the document.

AakashM
+1  A: 

This avoids the slow "//" operator.

count(/Shops/Shop/Product[type = 'Milk'])
Tomalak
Thanks It works fine some how the count(// doesn't give the expected result.If I want to count preceding Products from all shops (siblings and cousins) what would be a correct way to count that?
sofr
I'm sorry, but this must be homework. I think you should do your homework yourself. Also: Asking 15 questions and not accepting a single answer given is bad style. This web site does not work this way.
Tomalak
Thanks for letting me pay attention about accepting answers(I wasn't aware of that enough- I've closed al relevant questions)about this current question this is absolutely not homework!!!! sorry if it seems so! I'm a new develepor and got stuck by that point. I know this way count(preceding::node()) but when I try countI tried count(preceding::/Shops/Shop/Product[type = 'Milk']) but it has syntex error. actually my question is how to use preceding with the path :)
sofr
`count(preceding::Product[type = 'Milk'])`. Have a look at http://infohost.nmt.edu/tcc/help/pubs/xslt/axis-sect.html and the XPath language spec http://www.w3.org/TR/xpath
Tomalak
P.S.: It is also not strictly required to accept an answer in 100% of your questions. But those answers that actually *solved your problem* should be accepted at some point.
Tomalak