Click to See Complete Forum and Search --> : XSL for-each: is there a way to get the text value of the iterated element?


Engywook
06-23-2008, 05:55 PM
As I'm trying to wrap my mind around XSLT, there's something that's kinda bothering me.

XML snippet:

<answerList>
<answer>3</answer>
<answer>4</answer>
<answer right="right">5</answer>
</answerList>


XSL snippet, with problem area in bold:

<xsl:for-each select="answerList/answer">
<xsl:if test="@right='right'">&lt;b&gt;* * *</xsl:if>

<!--The selector below displays the first answer, 3, three times. I want to be able to display each answer.-->
<xsl:value-of select="../answer"/>

<xsl:if test="@right='right'">* * *&lt;/b&gt;</xsl:if>
<br/>
</xsl:for-each>


It appears that the only way to make it work is to add a child node to answer in the XML file:

<answerList>
<answer><answerText>3</answerText></answer>
<answer><answerText>4</answerText></answer>
<answer right="right"><answerText>5</answerText></answer>
</answerList>


...and invoke it with this XSL:

<xsl:for-each select="answerList/answer">
<xsl:if test="@right='right'">&lt;b&gt;* * *</xsl:if>

<xsl:value-of select="answerText"/>

<xsl:if test="@right='right'">* * *&lt;/b&gt;</xsl:if>


Do I really need to add a child node if I want to get the text out of a node where I'm using for-each? If you feel that this question reflects a lack of real understanding of XSL, you'd be right... I'm new to this and am finding it very counterintuitive.

Jeff Mott
06-23-2008, 08:11 PM
Instead of

<xsl:value-of select="../answer"/>

do

<xsl:value-of select="."/>

rpgfan3233
06-24-2008, 08:59 AM
Jeff is right. When you do "../answer", you're selecting the first answer element every time. :p

What you're looking for is indeed to select the current node (referred to as '.') because you're already inside each answer element when you iterate via xsl:for-each. Because you're inside the answer element already, when you add a child node and select it via xsl:value-of, it works. However, you have no child nodes inside the answer element, meaning the answer element itself has contents. As a result, you would need to select the current node.

I'm not sure if I helped or confused you more. :p

It sounds like you might have a slight bit of programming experience, so I'm sure it is the for-each concept that is tripping you up (most programming languages iterate over integer ranges, not items themselves).