xml - XSL - Adding Values of nodes based on condition -
so need function loops through xml nodes , if status true, adds value variable. aggregating social posts , need count how many of each social post in feed. here xml:
<feed> <channel> <sources> <source> <name>facebook</name> <count>3</count> </source> <source> <name>twitter</name> <count>2</count> </source> <source> <name>twitter</name> <count>8</count> </source> </sources> </channel> </feed>
the grab same source can appear multiple times, , need add together together. need twitter count of 10 above xml. here @ far:
<xsl:variable name="num_tw"> <xsl:for-each select="feed/channel/sources/source"> <xsl:choose> <xsl:when test="name, 'twitter')"> <xsl:value-of select="count"/> </xsl:when> <xsl:otherwise></xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:variable> <xsl:variable name="num_fb"> <xsl:for-each select="feed/channel/sources/source"> <xsl:choose> <xsl:when test="name, 'facebook')"> <xsl:value-of select="count"/> </xsl:when> <xsl:otherwise></xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:variable>
this doesn't work because if there 2 twitter feeds puts numbers side side , outputs "28" instead of "10". help appreciated!
you don't need iterate on nodes xsl:for-each here. instead can create utilize of sum operator. example, num_tw variable can re-written so
<xsl:variable name="num_tw" select="sum(feed/channel/sources/source[name='twitter']/count)"/>
however, want hard-code feed names here? 'grouping' issue, , in xslt 1.0 utilize technique called muencian grouping solve it. in case, want grouping source elements name element, , define key so:
<xsl:key name="source" match="source" use="name" />
then, @ source elements, , pick 1 first in grouping given name element:
<xsl:apply-templates select="feed/channel/sources/source[generate-id() = generate-id(key('source', name)[1])]" />
then, within template matches this, can sum counts so:
<xsl:value-of select="sum(key('source', name)/count)" />
here total xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="xml" indent="yes"/> <xsl:key name="source" match="source" use="name" /> <xsl:template match="/"> <xsl:apply-templates select="feed/channel/sources/source[generate-id() = generate-id(key('source', name)[1])]" /> </xsl:template> <xsl:template match="source"> <source> <xsl:copy-of select="name" /> <count><xsl:value-of select="sum(key('source', name)/count)" /></count> </source> </xsl:template> </xsl:stylesheet>
when applied xml, next output:
<source> <name>facebook</name> <count>3</count> </source> <source> <name>twitter</name> <count>10</count> </source>
note if did want find out count of specific feed, 'facebook' still preferably utilize key here. example:
<xsl:variable name="num_fb" select="sum(key('source', 'facebook')/count)"/>
xml xslt xslt-1.0
No comments:
Post a Comment