XSLT - How to evaluate a single node in multiple places
I am building an image rotator in XSLT that requires the following markup:
<div class="wrapper">
<div class="overlay"></div>
<div id="slider" class="slider">
[IMAGE FROM NODE A GOES HERE]
[IMAGE FROM NODE B GOES HERE]
...
</div>
<div id="htmlcaption" class="html-caption">
[CAPTION FOR NODE A GOES HERE]
[CAPTION FOR NODE B GOES HERE]
...
</div>
</div>
I need help constructing the XSLT so that Node A would get evaluated inside #slider then get re-evaluated in #htmlcaption, then No开发者_JAVA百科de B, and so on.
Any help would be greatly appreciated.
Thanks!
First, it is perfectly possible to evaluate a source element multiple times. Just use the same selector.
For example, considering the following XML:
<images>
<node id="a" image="foo.png" caption="foo" />
<node id="b" image="bar.png" caption="bar" />
</images>
This XSLT will repeatedly output stuff from the first node:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="images">
<div id="images">
<img><xsl:value-of select="node[@id='a']/@image"/></img>
<img><xsl:value-of select="node[@id='a']/@caption"/></img>
<img><xsl:value-of select="node[@id='a']/@image"/></img>
<img><xsl:value-of select="node[@id='a']/@caption"/></img>
</div>
</xsl:template>
Output:
<div id="images">
<img>foo.png</img>
<img>foo</img>
<img>foo.png</img>
<img>foo</img>
</div>
However it looks like what you really want is to loop over a bunch of nodes containing image and caption. You could use a for-each loop to avoid selecting the nodes by name:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="images">
<div id="images">
<xsl:for-each select="node">
<img><xsl:value-of select="@image"/></img>
</xsl:for-each>
</div>
<div id="captions">
<xsl:for-each select="node">
<div><xsl:value-of select="@caption"/></div>
</xsl:for-each>
</div>
</xsl:template>
</xsl:stylesheet>
Which will produce:
<div id="images">
<img>foo.png</img>
<img>bar.png</img>
</div>
<div id="captions">
<div>foo</div>
<div>bar</div>
</div>
精彩评论