我有以下XML来存储电影和演员:
<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>
前两个角色有一个具有唯一值的属性"actorID"。第三个参与者没有属性。我想将前两个参与者的名字显示为超链接,并显示第三个参与者名称为纯文本
这是我的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>
我得到的输出是以纯文本形式显示的Bob和John,而Mike根本不显示。所以它的作用正好相反
您的XPath:
<xsl:apply-templates select="cast/actors/actor[@actorID]/name"/>
导致模板只应用于具有actorID
属性的参与者。相反,这听起来像是你应该使用的:
<xsl:apply-templates select="cast/actors/actor/name"/>
那么XSLT应该像您期望的那样工作。
作为旁注,我建议在XSLT中使用文字元素,除非需要使用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>
它使XSLT更容易阅读。如果需要在属性中包含值,可以使用属性值模板:
<a href="http://www.mywebsite.com/actors?id={../@actorID}">