XSL - 根据条件添加节点的值

时间:2013-02-11 20:04:44

标签: xml xslt xslt-1.0

所以基本上我需要一个循环遍历XML节点的函数,如果条件为真,它会将该值添加到变量中。我正在汇总社交帖子,需要计算每个社交帖子中有多少是在Feed中。这是我的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>

catch是同一个源可以多次出现,我需要将它们加在一起。所以我需要上述XML的推文数为10。这是我到目前为止所处的位置:

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

这不起作用,因为如果有两个推特馈送它并排放数字并输出“28”而不是“10”。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:4)

您无需在此处使用 xsl:for-each 遍历节点。相反,您可以使用 sum 运算符。例如,您的 num_tw 变量可以像这样重写

<xsl:variable name="num_tw" select="sum(feed/channel/sources/source[name='Twitter']/count)"/>

但是,您真的想在此处对您的Feed名称进行硬编码吗?这实际上是一个“分组”问题,在XSLT 1.0中,您使用一种名为Muencian Grouping的技术来解决它。在您的情况下,您希望按名称元素对来源元素进行分组,因此您可以像这样定义一个键:

<xsl:key name="source" match="source" use="name" />

然后,您查看所有元素,然后选择组中第一个用于其名称元素的元素:

<xsl:apply-templates 
   select="feed/channel/sources/source[generate-id() = generate-id(key('source', name)[1])]" />

然后,在与此匹配的模板中,您可以总结计数:

<xsl:value-of select="sum(key('source', name)/count)" />

这是完整的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>

应用于XML时,输出以下内容:

<source>
   <name>Facebook</name>
   <count>3</count>
</source>
<source>
   <name>Twitter</name>
   <count>10</count>
</source>

请注意,如果您确实想要查找特定Feed的计数,例如“Facebook”,那么最好在这里使用密钥。例如:

<xsl:variable name="num_fb" select="sum(key('source', 'Facebook')/count)"/>
相关问题