This is kind of hard for me to express in English so an example might help. Let's say I have several elements called sentence which consists of several terms. In another part of XML there is a set of elements with language codes. I would like to apply a template for every sentence as many times as number of languages and call that template with appropriate language code. From this:
<description>
<sentences>
<sentence>
<term type="adjective">nice</term>
<term type="tripType">cycling</term>
</sentence>
<sentence>
<term type="adjective">boring</term>
<term type="tripType">hike</term>
</sentence>
</sentences>
<languages>
<l>cs</l>
<l>en</l>
</languages>
</description>
I want to produce something like this:
<div>
<p><span>cs</span> nice cycling</p>
<p><span>en</span> nice cycling</p>
</div>
<div>
<p><span>cs</span> boring hike</p>
<p><span>en</span> boring hike</p>
</div>
I was trying to use <xsl:for-each select="/description/languages/l"> but that sets the content of l as current element and I'm not able to get to the term stuff anymore.
Any idea would be greatly appreciated. Thanks
<xsl:template match="description">
<xsl:apply-templates select="sentences/sentence" />
</xsl:template>
<xsl:template match="sentence">
<xsl:variable name="terms" select="term" />
<div>
<xsl:for-each select="../../languages/l">
<p>
<span><xsl:value-of select="." /></span>
<xsl:apply-templates select="$terms" />
</p>
<xsl:for-each>
</div>
</xsl:template>
<xsl:template match="term">
<xsl:apply-templates select="." />
<xsl:if test="position() < last()"> </xsl:if>
</xsl:template>
This simple transformation (no explicit conditionals):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="sentence">
<xsl:variable name="vSentence" select="."/>
<div>
<xsl:for-each select="/*/languages/l">
<p>
<span><xsl:value-of select="."/></span>
<xsl:apply-templates select="$vSentence/term"/>
</p>
</xsl:for-each>
</div>
</xsl:template>
<xsl:template match="term[position() > 1]">
<xsl:text> </xsl:text>
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="l"/>
</xsl:stylesheet>
when applied on the provided XML document:
<description>
<sentences>
<sentence>
<term type="adjective">nice</term>
<term type="tripType">cycling</term>
</sentence>
<sentence>
<term type="adjective">boring</term>
<term type="tripType">hike</term>
</sentence>
</sentences>
<languages>
<l>cs</l>
<l>en</l>
</languages>
</description>
produces the wanted, correct result:
<div>
<p><span>cs</span>nice cycling</p>
<p><span>en</span>nice cycling</p>
</div>
<div>
<p><span>cs</span>boring hike</p>
<p><span>en</span>boring hike</p>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With