sharepointxsltsharepoint-2010dataviewwebpart

SharePoint Designer Data View- XSLT Count


I am working with a data view web part in SPD 2010. My xml structure is as follows:

<ProjectGroups>
    <ProjectGroup>
        <GroupID>1</GroupID>
        <ProjectName>Project 1</ProjectName>
    </ProjectGroup>
    <ProjectGroup>
        <GroupID>2</GroupID>
        <ProjectName>Project 2</ProjectName>
    </ProjectGroup>
    <ProjectGroup>
        <GroupID>2</GroupID>
        <ProjectName>Project 3</ProjectName>
    </ProjectGroup>
    </ProjectGroups>

This is a rollup web part, so what I am looking to do is get a count of Projects under each Project group. For my example above, Group ID 1 has 1 project, Group ID 2 has 2. I am sure there's a way to do this, but I'm sort of learning xslt on the fly, so I'm not sure exactly what to do. Any help is appreciated. Thanks.


Solution

  • This style-sheet ...

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    
    <xsl:key name="groups" match="ProjectGroup" use="GroupID" />
    
    <xsl:template match="@*|node()">
     <xsl:copy> 
       <xsl:apply-templates select="@*|node()" />
     </xsl:copy> 
    </xsl:template>
    
    <xsl:template match="ProjectGroup[generate-id()=generate-id(key('groups',GroupID)[1])]">
     <xsl:copy> 
       <xsl:apply-templates select="@*" />
       <xsl:attribute name="count-of-projects">
         <xsl:value-of select="count(key('groups',GroupID))" />
       </xsl:attribute>
       <xsl:apply-templates select="node()" />
     </xsl:copy> 
    </xsl:template>
    
    </xsl:stylesheet>
    

    ... when applied to your input, will produce ...

    <?xml version="1.0" encoding="utf-8"?>
    <ProjectGroups>
        <ProjectGroup count-of-projects="1">
            <GroupID>1</GroupID>
            <ProjectName>Project 1</ProjectName>
        </ProjectGroup>
        <ProjectGroup count-of-projects="2">
            <GroupID>2</GroupID>
            <ProjectName>Project 2</ProjectName>
        </ProjectGroup>
        <ProjectGroup>
            <GroupID>2</GroupID>
            <ProjectName>Project 3</ProjectName>
        </ProjectGroup>
    </ProjectGroups>