I need to write generic xsl that would take in an xml document and output the count of nodes and their names. So if I have a file like the following:
<assets>
<asset>
<type>hardware</type>
<item>
<name>HP laptop</name>
<value>799</value>
</item>
<item>
<name>server</name>
<value>1000</value>
</item>
<item>
<name>ViewSonic Monitor</name>
<value>399</value>
</item>
</asset>
<asset>
<type>software</type>
<item>
<name>Windows Vista</name>
<value>399</value>
</item>
<item>
<name>Office XP</name>
<value>499</value>
</item>
<item>
<name>Windows 7</name>
<value>399</value>
</item>
<item>
<name>MS Project Professional 2007</name>
<value>299</value>
</item>
</asset>
</assets>
The output would be:
<output>
<node name="assets" count="1"/>
<node name="asset" count="2"/>
<node name= "type" count="??"/>
<node name="item" count=??/>
<node name="name" count=??/>
<node name="value" count=??/>
</output>
Explanation: Using xsl:key , create a mapping from names to the nodes having that name. Then iterate through all unique names, and output the node count for the name. The main trick here is how to iterate through unique names. See the linked page for an explanation of the count(.
Use string-length(foo) - string-length(translate(foo, ',', '')) .
XSLT current() Function Usually the current node and the context node are the same. However, there is one difference. Look at the following XPath expression: "catalog/cd". This expression selects the <catalog> child nodes of the current node, and then it selects the <cd> child nodes of the <catalog> nodes.
XSLT is a functional language, not a procedural language, so you can't declare a counter. You can use xsl:number to get the position of the current node in its parent, if that helps. You can coerce a string to a number by using the XPath number() function.
You'll want to use the count function:
<xsl:value-of select="count(assets/asset)" />
So your code would look like:
Assets: <xsl:value-of select="count(assets)" />
Asset: <xsl:value-of select="count(assets/asset)" />
Item: <xsl:value-of select="count(assets/asset/item)" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With