XSL for-each: how to detect last node? - xslt

I have this simple code:
<xsl:for-each select="GroupsServed">
<xsl:value-of select="."/>,<br/>
</xsl:for-each></font>
I'm trying to add a comma for each item added.
This has 2 flaws:
Case of when there's only 1 item: the code would unconditionally add a comma.
Case of when there's more than 1 item: the last item would have a comma to it.
What do you think is the most elegant solution to solve this?
I'm using XSLT 2.0

If you're using XSLT 2.0, the canonical answer to your problem is
<xsl:value-of select="GroupsServed" separator=", " />
On XSLT 1.0, the somewhat CPU-expensive approach to finding the last element in a node-set is
<xsl:if test="position() = last()" />

Final answer:
<xsl:for-each select="GroupsServed">
<xsl:value-of select="."/>
<xsl:choose>
<xsl:when test="position() != last()">,<br/></xsl:when>
</xsl:choose>
</xsl:for-each>

<xsl:variable name="GROUPS_SERVED_COUNT" select="count(GroupsServed)"/>
<xsl:for-each select="GroupsServed">
<xsl:value-of select="."/>
<xsl:if test="position() < $GROUPS_SERVED_COUNT">
,<br/>
</xsl:if>
</xsl:for-each></font>

Insert the column delimiter before each new item, except the first one. Then insert the line break outside the for-each loop.
<xsl:for-each select="GroupsServed">
<xsl:if test="position() != 1">,</xsl:if>
<xsl:value-of select="."/>
</xsl:for-each>
<br/>
In other words, treat every item like the last item. The exception is that the first item does not need a comma separator in front of it. The loop ends after the last item is processed, which also tells us where to put the break.

Related

XSLT 2.0 how to test for position() in tokenize() on output

In XSLT 2.0 I have a parameter than comes in as a delimited string of document names like:
ms609_0080.xml~ms609_0176.xml~ms609_0210.xml~ms609_0418.xml
I tokenize() this string and cycle through it with xsl:for-each to pass each document to a key. The results from the key I then assemble into a comma-delimited string to output to screen.
<xsl:variable name="list_of_corresp_events">
<xsl:variable name ="tokenparam" select="tokenize($paramCorrespdocs,'~')"/>
<xsl:for-each select="$tokenparam">
<xsl:choose>
<xsl:when test=".[position() != last()]">
<xsl:value-of select="document(concat($paramSaxondatapath, .))/(key('correspkey',$correspid))/#xml:id"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat(document(concat($paramSaxondatapath, .))/(key('correspkey',$correspid))/#xml:id, ', ')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:variable>
Everything works fine except that when I output the variable $list_of_corresp_events it looks like the following, with an unexpected trailing comma:
ms609-0080-2, ms609-0176-1, ms609-0210-1, ms609-0418-1,
Ordinarily the last comma should not appear based on test=".[position() != last()]" ? Possibly positions don't work for tokenized data? I didn't see a way to apply string-join() to this.
Many thanks.
Improving on the solution from #zx485, try
<xsl:for-each select="$tokenparam">
<xsl:if test="position()!=1">, </xsl:if>
<xsl:value-of select="document(concat($paramSaxondatapath, .))/(key('correspkey',$correspid))/#xml:id"/>
</xsl:for-each>
Two things here:
(a) you don't need to repeat the same code in both conditional branches
(b) it's more efficient to output the comma separator before every item except the first, rather than after every item except the last. That's because evaluating last() involves an expensive look-ahead.
Change
<xsl:when test=".[position() != last()]">
to
<xsl:when test="position() != last()">
Then it should all work as desired.
It seems you can simplify this to
<xsl:variable name="list_of_corresp_events">
<xsl:value-of select="for $t in tokenize($paramCorrespdocs,'~') document(concat($paramSaxondatapath, $))/(key('correspkey',$correspid))/#xml:id" separator=", "/>
</xsl:variable>
or with string-join
<xsl:variable name="list_of_corresp_events" select="string-join(for $t in tokenize($paramCorrespdocs,'~') document(concat($paramSaxondatapath, $))/(key('correspkey',$correspid))/#xml:id, ', ')"/>

XSLT 2.0 tokenising delimiters within delimiters

In XSLT 2.0 I have long string (parameter) with a delimiter (;) inside a delimiter (~), more specifically a triplet inside a delimiter.
Data is organized like so:
<parameter>qrsbfs;qsvsv;tfgz~dknk;fvtea;gtvath~pksdi;ytbdi;oiunhu</parameter>
The first tokenize($mystring,'~') in a for-each produces :
qrsbfs;qsvsv;tfgz
dknk;fvtea;gtvath
pksdi;ytbdi;oiunhu
Within that tokenization, I need to treat it by looping again:
qrsbfs
qsvsv
tfgz
dknk
fvtea
gtvath
pksdi
ytbdi
oiunhu
I can do intensive string manipulation to get there using concat, string-length, and substring-before/substring-after, but I wondered if there wasn't a more elegant solution that my neophyte mind wasn't overlooking?
EDIT, adding nested tokenize that returned incorrect results:
<xsl:for-each select="tokenize($myparameter,'~')">
<xsl:for-each select="tokenize(.,';')">
<xsl:if test="position()=1">
<xsl:value-of select="."/>
</xsl:if>
<xsl:if test="position()=2">
<xsl:value-of select="."/>
</xsl:if>
<xsl:if test="position()=3">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:for-each>
If you wanted a one line solution, you could do something like this, using nested for-in-return statements:
<xsl:sequence select="for $n in tokenize(.,'~') return concat(string-join(tokenize($n,';'),'
'),'
')"/>
If you don't need to tokenize them separately, you could replace the ~ with ; and tokenize all 9 elements at the same time:
tokenize(replace(parameter,'~',';'),';')
For what it's worth, the code in https://xsltfiddle.liberty-development.net/pPqsHUe uses
<xsl:template match="parameter">
<xsl:for-each select="tokenize(., '~')">
<xsl:value-of select="tokenize(., ';')" separator="
"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
and with output method text produces
qrsbfs
qsvsv
tfgz
dknk
fvtea
gtvath
pksdi
ytbdi
oiunhu

Show the separator once only the 2nd value exist

<handlingInstruction>
<handlingInstructionText>CTAC | MARTINE HOEYLAERTS</handlingInstructionText>
</handlingInstruction>
<handlingInstruction>
<handlingInstructionText>PHON | 02/7225235</handlingInstructionText>
</handlingInstruction>
I have The above given xml structure I concatenate them and use a comma as a separator using below code
> <xsl:value-of
> select="concat(handlingInstruction[1]/handlingInstructionText,
> ',',
> handlingInstruction[2]/handlingInstructionText)"/>
I would like to ask how will I make the comma separator appear only once the 2nd exist the shortest way possible. Thanks in advance
If you don't want to use xsl:for-each, try:
<xsl:template match="/root">
<xsl:apply-templates select="handlingInstruction/handlingInstructionText"/>
</xsl:template>
<xsl:template match="handlingInstructionText">
<xsl:value-of select="."/>
<xsl:if test="position()!=last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:template>
(continued from here: https://stackoverflow.com/a/34679465/3016153)
<xsl:for-each select="handlingInstruction">
<xsl:value-of select="handlingInstructionText"/>
<xsl:if test="position()!=last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
This will iterate over all handlingInstruction elements and output the value of the handlingInstructionText element. It will add to the end of each element, if it is not the last one (which the first one would be if there was only one), a comma.
In your example, you only used two handlingInstruction elements. If you want to only use two with this method, do
<xsl:for-each select="handlingInstruction[position()<3]">
<xsl:value-of select="handlingInstructionText"/>
<xsl:if test="position()!=last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
Note the < there. That is actually a less than sign (<), but we can't use that in xml so we use the entity defined for it.
Here is a second way to do it, which avoids the for-each loop.
If you are using xslt version 2, there is a string-join function which could be used like:
<xsl:value-of select="string-join(//handlingInstruction/handlingInstructionText,',')"/>
The string-join method takes a sequence of strings (which the nodes selected will be converted to by taking their content) and concatenates them with the separator. If there is only one string, a separator will not be added.
Alternatively, xslt 2 also provides a separator attribute on the value-of element. Thus
<xsl:value-of select="//handlingInstruction/handlingInstructionText" separator=","/>
produces the same result.

XSLT 1.0: if statement when position matches a variable value

I'm trying to insert an IF statement into an existing FOR-EACH loop to do something slightly different if it matches a variable from another node (the node I want is actually a sibling of it's parent - if that makes sense!?).
The value is a simple integer. I basically want to say: If the position is equal to the variable number then do XXXX.
Here is the XSLT, it's only v1.0 and not 2.0 that I can use.
<xsl:for-each select="/Properties/Data/Datum[#ID='ID1']/DCR[#Type='accordion_tab']/accordion_tab/sections">
<h3 class="accordionButton">
<xsl:if test="position()='openpane value to go here'">
<xsl:attribute name="class">
<xsl:text>new text</xsl:text>
</xsl:attribute>
</xsl:if>
</xsl:for-each>
My XML extract is here:
<sections>
<title>title</title>
<text>some text</text>
</sections>
<openpane>2</openpane>
You didn't make this clear in your question, but I assume you iterate over the sections elements in your for-each loop. From the for-each loop you can reach the openpane element by going through the parent of the current sections element:
<xsl:for-each select="sections">
<xsl:if test="position() = ../openpane">
...
</xsl:if>
</xsl:for-each>
You could also define a variable referring to the openpane element first:
<xsl:variable name="openpane" select="openpane"/>
<xsl:for-each select="sections">
<xsl:if test="position() = $openpane">
...
</xsl:if>
</xsl:for-each>

XSL for each loop selecting position of first occurrence

In the following code snippet, I'm trying to get position of EMP_ID field from the available fields. This works fine if there's just one occurrence of EMP_ID.
But if there are more than one occurences then variable 'empid_field' will have positions of all the occurrences appended one after the other. i.e if EMP_ID is at postions 1, 8, and 11, then 'empid_field' would be '1811'.
Is there any way I get position of first occurrence only? Or Can I get comma separated positions atleast? (Code sample would be highly appreciated as I'm new to XSL programming)
<xsl:variable name="empid_field">
<xsl:for-each select="$fields">
<xsl:if test="internalName='EMP_ID'">
<xsl:value-of select="position()"/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
The easiest solution which is in my mind is to extend this. But I think there are also solutions which look more pretty.
<xsl:variable name="empid_field">
<xsl:for-each select="$fields">
<xsl:if test="internalName='EMP_ID'">
<xsl:value-of select="position()"/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="first_empid_field">
<xsl:value-of select="$empid_field[1]"/>
</xsl:variable>
The variable $first_empid_field will only have the first position value.
Ok got something ...
Created a comma separated string and picked the part before the delimiter.
<xsl:variable name="empid_fields" >
<xsl:for-each select="$fields">
<xsl:if test="internalName='EMP_ID'">
<xsl:value-of select="position()" />
<xsl:text >, </xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="empid_field" >
<xsl:value-of select="substring-before($empid_fields, ', ')" />
</xsl:variable>