Check if a variable of the for-each is equal with an XML entry
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&g开发者_如何转开发t;
Output:
<option value="1">Album #1</option>
<option value="2" selected="selected">Album #2</option>
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">
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">
<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>
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
.
精彩评论