Reputation: 876
I have the following XML that stores movies and actors:
<movies
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="movies.xsd">
<movie movieID="1">
<cast>
<actors>
<actor actorID="1">
<name>Bob</name>
</actor>
<actor actorID="2">
<name>John</name>
</actor>
<actor>
<name>Mike</name>
</actor>
</actors>
</cast>
</movie>
</movies>
The first two actors have an attribute "actorID" with a unique value. The third actor has no attributes. I would like to display the first two actors' names as hyperlinks and display the third actor name as plain text.
This is my XSLT:
<xsl:template match="/">
<xsl:apply-templates select="movies/movie" />
</xsl:template>
<xsl:template match="movie">
<xsl:text>Actors: </xsl:text>
<xsl:apply-templates select="cast/actors/actor[@actorID]/name"/>
</xsl:template>
<xsl:template match="actor[@actorID]/name">
<xsl:element name="a">
<xsl:attribute name="href">www.mywebsite.com</xsl:attribute>
<xsl:value-of select="." />
</xsl:element>
<xsl:element name="br" />
</xsl:template>
<xsl:template match="actor/name">
<xsl:value-of select="." />
<xsl:element name="br" />
</xsl:template>
The output that I get is Bob and John displayed as plain text, and Mike not displayed at all. So it does pretty much the opposite of what I want to achieve.
Upvotes: 0
Views: 1816
Reputation: 101768
Your XPath here:
<xsl:apply-templates select="cast/actors/actor[@actorID]/name"/>
is causing templates to only be applied to actors that have an actorID
attribute. Instead, it sounds like this is what you should be using:
<xsl:apply-templates select="cast/actors/actor/name"/>
Then the XSLT should behave like you expect.
As a side note, I would advise using literal elements in your XSLT, unless there's a need to use xsl:element
:
<xsl:template match="actor[@actorID]/name">
<a href="http://www.mywebsite.com">
<xsl:value-of select="." />
</a>
<br />
</xsl:template>
<xsl:template match="actor/name">
<xsl:value-of select="." />
<br />
</xsl:template>
It makes the XSLT easier to read IMHO. If you need to include values in an attribute, you can use attribute value templates:
<a href="http://www.mywebsite.com/actors?id={../@actorID}">
Upvotes: 2