如何使用xslt计算特定节点

时间:2014-12-02 17:07:32

标签: xml xslt

我有以下xml

<color>
   <title>white</title>
</color>
<color>
   <title>black</title>
</color>
<color>
   <title>white</title>
</color>
<color>
   <title>black</title>
</color>
<color>
   <title>white</title>
</color>

我需要获得count colortitle个节点white等于&#39; xslt&#39;使用{{1}}

即获得结果: 3

由于

2 个答案:

答案 0 :(得分:1)

你需要一些XSLT来开始,你需要有效的XML(只有一个根元素)。

我需要你提供这两个以便给你一个完整的答案,但基本上,你可以使用count()函数和谓词:

<xsl:value-of select="count(//color[title = 'white'])" />

更完整的例子:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/">
      <n>
        <xsl:value-of select="count(//color[title = 'white'])"/>
      </n>
    </xsl:template>
</xsl:stylesheet>

答案 1 :(得分:1)

解决方案:count(color[./title='white'])

请尝试以下代码

 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="1.0">
 <xsl:template match="*">
    <Value>
        <xsl:value-of select="count(color[./title='white'])"/>
    </Value>
 </xsl:template>
 </xsl:stylesheet>

输出:<Value>3</Value>