使用xsl选择子节点组

时间:2012-10-24 08:50:06

标签: xml xslt foreach

我正在尝试使用for-each来选择和显示一组子节点,我被困住了!

XML

<cta>
    <text>Call to action text</text>
    <link>call to action link location</link>
    <alt>call to action alt text</alt>
    <target>_blank</target>
    <style>button blueBut</style>
</cta>
<cta>
    <text>Call to action 2</text>
    <link>call to action 2 link</link>
    <alt>call to action 2 alt text</alt>
    <target>_blank</target>
    <style>button blueBut</style>
</cta>

XSL

<div class="buttonPostLeft">    
    <xsl:for-each select="/Properties/Data/Datum[@ID='ID1']/DCR[@Type='Overview']/overview/cta/*">
        <a>
            <xsl:attribute name='class'>
                <xsl:value-of select="/Properties/Data/Datum[@ID='ID1']/DCR[@Type='Overview']/overview/cta/style" />
            </xsl:attribute>
            <xsl:attribute name='href'>
                <xsl:value-of select="/Properties/Data/Datum[@ID='ID1']/DCR[@Type='Overview']/overview/cta/link" />
            </xsl:attribute>
            <xsl:attribute name='title'>
                <xsl:value-of select="/Properties/Data/Datum[@ID='ID1']/DCR[@Type='Overview']/overview/cta/alt" />
            </xsl:attribute>
            <xsl:value-of select="/Properties/Data/Datum[@ID='ID1']/DCR[@Type='Overview']/overview/cta/text"/>
        </a>
    </xsl:for-each>
</div>

我基本上希望使用该组属性为XML树中的每个cta组重复锚标记。所以在这个例子中,DIV中会有2个链接。希望这有点意义!

1 个答案:

答案 0 :(得分:2)

在你的for-each中,你现在使用<cta>循环遍历任何匹配的/cta/*的所有子节点

您需要更改

/Properties/Data/Datum[@ID='ID1']/DCR[@Type='Overview']/overview/cta/*

/Properties/Data/Datum[@ID='ID1']/DCR[@Type='Overview']/overview/cta

此外,一旦你进入for-each循环,你可以通过使用一个点来匹配其中的元素,如下所示:

<xsl:attribute name='class'>
    <xsl:value-of select="./style" />
</xsl:attribute>

甚至更整洁的东西会是这样的:

<a class="{./style}" href="{./link}" title="{./alt}">
    <xsl:value-of select="./text"/>
</a>