tags:

views:

23

answers:

3

I'm trying to add the attribute 'selected' to <option>. I've tried various ways and I can't get it working. This is how I'm trying it:

<xsl:for-each select="page/index/values/albums">
    <option>
        <xsl:attribute name="value"><xsl:value-of select="id" /></xsl:attribute>
        <xsl:if test="page/index/values/album = id">
             <xsl:attribute name="selected">selected</xsl:attribute>
        </xsl:if>
        <xsl:value-of select="name" />
    </option>
</xsl:for-each>

What is the correct form for the <xsl:if />?

Edit:

My XML file:

<page>
    <index>
        <values>
            <album>2</album>

            <albums>
                <id>1</id>
                <name>Album #1</name>
            </albums>

            <albums>
                <id>2</id>
                <name>Album #2</name>
            </albums>
        </values>
    </index>
</page>

Output:

<option value="1">Album #1</option>
<option value="2" selected="selected">Album #2</option>
+1  A: 

The XPath you are using is incorrect:

<xsl:if test="page/index/values/album = id">

Is should be:

<xsl:if test="../album = id">

You are in the context of the different albums nodes, so you need to go to the parent node values before getting the value of album.

Alternatively, you need to root your XPath:

<xsl:if test="/page/index/values/album = id">
Oded
I added the XML file that I'm transforming. page/index/values/albums have nothing to do with page/index/values/album .The second is the id of the selected album for a `<select>`.
Isern Palaus
+1  A: 

The test condition should be:

id = ../album

Edit: Now with desired output, use this stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <xsl:template match="values">
        <select>
            <xsl:apply-templates select="albums"/>
        </select>
    </xsl:template>
    <xsl:template match="albums">
        <option value="{id}">
            <xsl:apply-templates/>
        </option>
    </xsl:template>
    <xsl:template match="id"/>
    <xsl:template match="id[.=../../album]">
        <xsl:attribute name="selected">selected</xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

Output:

<select>
    <option value="1">Album #1</option>
    <option value="2" selected="selected">Album #2</option>
</select>
Alejandro
A: 

Your form for adding an attribute is right, but as @Alejandro pointed out, your if test condition is probably wrong. Especially the left side of the "=". These XPath expressions are relative to the context node, which is page/index/values/albums.

LarsH