如何为不连续的元素中断XSLT for-each循环?

问题描述:

我有一个具有以下结构的结构化XML:

I have a structured XML with this structure:

<root>
  <item/>
  <item/>
  <something/>
  <item/>
</root>

如果我使用这样的东西:

If I use something like this:

<xsl:for-each select="/root/item">

它将选择列表中的所有item元素.我想在第二个item之后中断循环,因为在第二个和第三个之间有一个something元素.

it will pick all the item elements inside the list. I want to interrupt the loop after the second item, because between the 2nd and the 3rd there is a something element.

我怎么能得到这个?

在XSLT中,不可能发生<xsl:for-each><xsl:apply-templates>的突围" ,除了使用您可能不想要的<xsl:message terminate="yes"/>.这是由于XSLT是一种功能语言,并且与任何功能语言一样,没有任何执行顺序"概念-例如,代码可以在所有程序上并行执行 .选定的节点.

In XSLT there isn't any possibility for a "break" out of an <xsl:for-each> or out of <xsl:apply-templates>, except using <xsl:message terminate="yes"/> which you probably don't want. This is due to the fact that XSLT is a functional language and as in any functional language there isn't any concept of "order of execution" -- for example the code can be executing in parallel on all the nodes that are selected.

解决方案是在select属性中指定一个表达式,精确选择 所需节点.

The solution is to specify in the select attribute an expression selecting exactly the wanted nodes.

使用:

<xsl:for-each select="/*/*[not(self::item)][1]/preceding-sibling::*">
 <!-- Processing here -->
</xsl:for-each>

这将选择要处理的顶层元素的第一个子元素的所有先前同级元素,而不是item -这意味着相邻的item元素的起始组是顶层元素的第一个子元素.

This selects for processing all preceding elements siblings of the first child element of the top element that isn't item -- that means the starting group of adjacent item elements that are the first children of the top element.