如何将XSLT模板应用于元素的次数与文档中另一个元素的数量相同?

时间:2012-05-03 08:23:54

标签: xml xslt xpath

这对我来说很难用英语表达,所以一个例子可能有所帮助。假设我有几个叫做句子的元素,它由几个术语组成。在XML的另一部分中,有一组带有语言代码的元素。我想为每个句子应用一个与模板数量相同的模板,并使用适当的语言代码调用该模板。由此:

<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>

我想生产这样的东西:

<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>

我尝试使用<xsl:for-each select="/description/languages/l">但是将l的内容设置为当前元素,我无法再使用该术语。

任何想法都会非常感激。感谢

3 个答案:

答案 0 :(得分:1)

<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() &lt; last()"> </xsl:if>
</xsl:template>

答案 1 :(得分:1)

这个简单的转换(没有明确的条件)

<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>

应用于提供的XML文档

<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>

生成想要的正确结果

<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>

答案 2 :(得分:0)

你可以将当前元素(术语东西,如果我已经正确理解)分配给变量,然后在for-each循环中使用该变量:<xsl:variable name="term" select="current()"/>