/ / Conteggio valori virgola XSLT conteggio - xslt, xslt-1.0

Conteggio valori virgola XSLT conteggio - xslt, xslt-1.0

Ho un valore come intero = "1,2,3,4,5" nell'xml. Come posso contare il numero totale usando XSLT. In modo che l'output mi dà un conteggio di 5

Saluti, Sam

risposte:

0 per risposta № 1

Ecco un modo (potrebbero essercene altri). Trasforma semplicemente tutte le virgole in stringhe vuote, quindi confronta la differenza di lunghezza delle stringhe:

<xsl:value-of
select="string-length(@integer)
- string-length(translate(@integer, ",", "")) + 1" />

Se hai bisogno di gestire stringhe vuote, prova questo

<xsl:value-of
select="string-length(@integer)
- string-length(translate(@integer, ",", ""))
+ 1 * (string-length(@integer) != 0)" />

0 per risposta № 2

Se si desidera contare i valori separati da virgole, ma ANCHE essere in grado di fare riferimento ai singoli elementi, è possibile utilizzare un modello ricorsivo come tale.

Questo foglio di stile XSLT 1.0 convertirà i valori separati da virgole in nodi e poi li contatterà ...

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:output method="text"/>

<xsl:template match="/">
<xsl:variable name="as-nodes">
<xsl:call-template name="parse-comma-separated-values">
<xsl:with-param name="csv" select="t/@csv" />
</xsl:call-template>
</xsl:variable>
<xsl:value-of select="count(msxsl:node-set($as-nodes)/*)" />
</xsl:template>

<xsl:template name="parse-comma-separated-values">
<xsl:param name="csv" />
<xsl:choose>
<xsl:when test="$csv = """/>
<xsl:when test="not( contains( $csv, ","))">
<value-node value="{$csv}" />
</xsl:when>
<xsl:otherwise>
<value-node value="{substring-before($csv,",")}" />
<xsl:call-template name="parse-comma-separated-values">
<xsl:with-param name="csv" select="substring-after($csv,",")"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

</xsl:stylesheet>

... se applicato a questo documento di input ...

 <t csv="1,2,3,4,5"/>

... produce ...

 5