Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node count and occurence - XSL

Tags:

xml

xslt

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>
like image 955
user182093 Avatar asked Sep 30 '09 20:09

user182093


People also ask

How do I count nodes in XSLT?

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(.

How do I count characters in XSLT?

Use string-length(foo) - string-length(translate(foo, ',', '')) .

What does node () do in XSLT?

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.

How do you set a counter in XSLT?

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.


1 Answers

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)" />
like image 164
Gavin Miller Avatar answered Sep 20 '22 10:09

Gavin Miller