【问题标题】:XSLT - hyperlink an XML element based on its attributeXSLT - 超链接基于其属性的 XML 元素
【发布时间】:2015-02-11 07:01:29
【问题描述】:

我有以下存储电影和演员的 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 根本没有显示。所以它的作用几乎相反 我想要达到的目标。

【问题讨论】:

    标签: xml xslt hyperlink


    【解决方案1】:

    你的 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}">
    

    【讨论】:

    • 感谢您的回复,JLRishe。我已将您的解决方案应用于我的代码,现在 Bob、John 和 Mike 显示为纯文本。似乎第二个模板匹配覆盖了第一个。
    • 您是否修改了这一行:&lt;xsl:template match="actor[@actorID]/name"&gt;?那个应该保持不变,只是应该修改apply-templates。如果您只修改了apply-templates,而第二个模板仍然覆盖第一个模板,您可以尝试为第一个模板添加优先级属性:&lt;xsl:template match="actor[@actorID]/name" priority="2"&gt;
    • 优先级属性完成了这项工作。这表明有多少种方法可以解决 xslt 中的问题。一如既往,非常感谢您的帮助,JLRishe。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多