![](/img/trans.png)
[英]How to select xml element based on its attribute value start with “Heading” in xslt?
[英]XSLT - hyperlink an XML element based on its attribute
我有以下存储电影和演员的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>
前两个actor具有一个具有唯一值的属性“actorID”。 第三个演员没有属性。 我想将前两个actor的名称显示为超链接,并将第三个actor名称显示为纯文本。
这是我的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
属性的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}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.