如何提取B为“红色”的前两个C值(“Baby”和“Cola”)?输入实例为:
<Root>
<A>
<B>BLACK</B>
<C>Apple</C>
</A>
<A>
<B>RED</B>
<C>Baby</C>
</A>
<A>
<B>GREEN</B>
<C>Sun</C>
</A>
<A>
<B>RED</B>
<C>Cola</C>
</A>
<A>
<B>RED</B>
<C>Mobile</C>
</A>
</Root>输出实例必须为:
<Root>
<D>Baby</D>
<D>Cola</D>
</Root>我考虑了for-each和全局变量的组合。但在XSLT中,不可能通过更改全局变量的值来中断for-each。我再也不知道了。
发布于 2011-06-23 21:22:15
不需要破坏for-each:
<xsl:template match="Root">
<xsl:copy>
<xsl:for-each select="(A[B='RED']/C)[position() < 3]">
<D><xsl:value-of select="." /></D>
</xsl:for-each>
</xsl:copy>
</xsl:template>发布于 2011-06-23 22:44:57
这可以用xsl:key很好地解决。
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:key name="kB" match="A" use="B" />
<xsl:template match="Root">
<xsl:copy>
<xsl:apply-templates select="key('kB', 'RED')[position() < 3]" />
</xsl:copy>
</xsl:template>
<xsl:template match="A">
<D><xsl:value-of select="C" /></D>
</xsl:template>
</xsl:stylesheet>通过您的输入,给出
<Root>
<D>Baby</D>
<D>Cola</D>
</Root>发布于 2011-06-23 21:33:25
不需要迭代,只需将模板应用于所需的元素:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="Root">
<Root>
<xsl:apply-templates select="A/B[
.='RED'
and
count(../preceding-sibling::A[B='RED'])<2]"/>
</Root>
</xsl:template>
<xsl:template match="B">
<D>
<xsl:value-of select="following-sibling::C"/>
</D>
</xsl:template>
</xsl:stylesheet>当应用于您的输入时,会给出:
<Root>
<D>Baby</D>
<D>Cola</D>
</Root>https://stackoverflow.com/questions/6454623
复制相似问题