假设下面的XML输入...根据XSL中的条件动态输出元素?
<incidents>
<incident>
<year>2011</year>
<other data here>
</incident>
<incident>
<year>2009</year>
<other data here>
</incident>
<incident>
<year>2006</year>
</incident>
</incidents>
的XML总是逐年预先排序,以便最近发生的事件今年是第一次。我需要使用xsl来处理它,并且基本上以最少的转换输出数据,最多5年,但如果缺少任何年份,我只需要输出<incident><year>missingYear</year></incident>
的元素。
因此,假设我有正确的XSL要做到这一点,处理上面的XML将产生此...
<incidents>
<incident>
<year>2011</year>
</incident>
<incident>
<year>2010</year>
</incident>
<incident>
<year>2009</year>
</incident>
<incident>
<year>2008</year>
</incident>
<incident>
<year>2007</year>
</incident>
<incident>
<year>2006</year>
</incident>
</incidents>
我能走到今天与XSL,但它不占之间较大的差距年
<xsl:variable name="maxYear" select="/incidents/incident/year[1]"></xsl:variable>
<xsl:template match="incidents" >
<xsl:element name="incident">
<xsl:for-each select="incident">
<xsl:variable name="currentYear" select="year"/>
<xsl:choose>
<xsl:when test="($maxYear - (position() -1)) != $currentYear">
<!-- output the missing year -->
<xsl:element name="year"> <xsl:value-of select="($maxYear - (position() -1))" /></xsl:element>
<!-- output the current year node -->
<xsl:element name="year"> <xsl:value-of select="$currentYear" /></xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:element name="year"> <xsl:value-of select="$currentYear" /></xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:element>
</xsl:template>
我已经更新了原来的问题,但现在回想起来,我认为你是对的....我可以得到当年的XSL,然后就回送从他们的5次,每次检查是否'year'在源xml中可用,如果没有,只需创建该元素。不知道为什么我让我的难度超过需求;感谢您的启发 – raffian 2012-02-01 02:01:32