如何将模板应用于for-each中的每个选定节点? [英] How do I apply templates to each selected node in a for-each?

查看:83
本文介绍了如何将模板应用于for-each中的每个选定节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我在这里丢失了一些东西.在下面的XSLT转换中,实际结果与预期结果不符.

I know I'm missing something here. In the XSLT transformation below, the actual result doesn't match the desired result.

for-each内,我想将match="track"模板应用于每个选定的track元素.如果我对XSLT的理解正确,那么在当前设置下,仅将每个选定的track元素的子节点与模板进行匹配,而不是与track元素本身进行匹配.

Inside the for-each, I want to apply the match="track" template to each selected track element. If I've understood XSLT properly, with the current setup only child nodes of each selected track element are matched against templates, not the track elements themselves.

如何使track元素按需要通过模板?我需要重新考虑整个方法吗?

How can I make the track elements go through the template as desired? Do I need to rethink my entire approach?

注意:转换是使用PHP执行的.为简便起见,省略了XML声明.

XML文档:

<album>
    <title>Grave Dancers Union</title>
    <track id="shove">Somebody To Shove</track>
    <track id="gold">Black Gold</track>
    <track id="train">Runaway Train</track>
    <producer>Michael Beinhorn</producer>
</album>

XSL样式表:

<xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/album">
        <ol>
            <xsl:for-each select="track">
                <li><xsl:apply-templates/></li>
            </xsl:for-each>
        </ol>
    </xsl:template>

    <xsl:template match="track">
        <a href="{@id}"><xsl:apply-templates/></a>
    </xsl:template>
</xsl:stylesheet>

结果:

<ol>
    <li>Somebody To Shove</li>
    <li>Black Gold</li>
    <li>Runaway Train</li>
</ol>

所需结果:

<ol>
    <li><a href="shove">Somebody To Shove</a></li>
    <li><a href="gold">Black Gold</a></li>
    <li><a href="train">Runaway Train</a></li>
</ol>

推荐答案

我同意'ndim'的观点,即您可能应该重组XSLT以消除xsl:for-each循环.

I would agree with 'ndim' that you should probably restructure your XSLT to do away with the xsl:for-each loop.

或者,您可以修改xsl:apply-templates以在xsl:for-each中选择当前轨道节点

Alternatively, you could amend the xsl:apply-templates to select the current track node within the xsl:for-each

<xsl:for-each select="track">
   <li>
      <xsl:apply-templates select="." />
   </li>
</xsl:for-each>

如果需要,保持xsl:for-each至少可以让您以其他顺序对轨道进行排序.

Keeping the xsl:for-each would, at least, allow you to sort the tracks in another order, if desired.

这篇关于如何将模板应用于for-each中的每个选定节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆