Count how many nodes have the same value of a child node (wi

Here should go questions about transforming XML with XSLT and FOP.
Monique7
Posts: 1
Joined: Sat Nov 30, 2013 10:53 pm

Count how many nodes have the same value of a child node (wi

Post by Monique7 »

Hello,
I'd like to Count how many nodes have the same value of a child node and display the list(with xslt using variables)

The xml is smth like this:

Code: Select all


<list>
<student>
<name>Student1</name>
<major>Chemistry</major>
<email>st1@example.com</email>
</student>
<student>
<name>Student2</name>
<major>Chemistry</major>
<email>st2@example.com</email>
</student>
<student>
<name>Student3</name>
<major>Engineering</major>
<email>st3@example.com</email>
</student>
<student>
<name>Student4</name>
<major>Chemistry</major>
<email>st4@example.com</email>
</student>
</list>
I want to count how many students are at every major and display the list, so smth like this:

Chemistry - 3
Student1
Student2
Student4
Engineering - 1
Student3
...
Jamil
Posts: 97
Joined: Thu Oct 23, 2008 6:29 am

Re: Count how many nodes have the same value of a child node

Post by Jamil »

The XPath to do this is relatively simple:

count(/list/student[major='Chemistry'])

If you want to do that in an XSLT, you can do a variable replacement for the major.
Jamil
Posts: 97
Joined: Thu Oct 23, 2008 6:29 am

Re: Count how many nodes have the same value of a child node

Post by Jamil »

I'm not sure if you had issues doing this. In case you have, here is a stylesheet that works with your example XML. Note that this is a version 2.0 stylesheet that makes use of the distinct-values function. This will work fine within Oxygen, but if you are doing this in code, you must use a 2.0 XSLT processor:

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">

<xsl:output method="text"/>

<xsl:template match="/">
<xsl:variable name="majors">
<xsl:for-each select="distinct-values(/list/student/major)">
<xsl:element name="major"><xsl:value-of select="."/></xsl:element>
</xsl:for-each>
</xsl:variable>

<xsl:variable name="students">
<xsl:copy-of select="/list/student"/>
</xsl:variable>

<xsl:for-each select="$majors/major">
<xsl:variable name="major"><xsl:value-of select="."/></xsl:variable>
<xsl:value-of select="$major"/> - <xsl:value-of select="count($students/student[major=$major])"/><xsl:text>&#xa;</xsl:text>
<xsl:for-each select="$students/student[major=$major]/name"><xsl:value-of select="."/><xsl:text>&#xa;</xsl:text></xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The output from this stylesheet is below:

Code: Select all

Chemistry - 3
Student1
Student2
Student4
Engineering - 1
Student3
Post Reply