How-to break a for-each loop in XSLT?

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

How-to break a for-each loop in XSLT?

回答1:

XSLT is written in a very functional style, and in this style there is no equivalent of a break statement. What you can do is something like this:

         ...body of loop...     

That way the for-each will still iterate through all the nodes, but the body of the loop will only be executed if the condition is true.



回答2:

Put the condition for stopping the "loop" in the select attribute of the for-each element. For instance, to "break" after four elements:

To iterate up to but not including a node that satisfied some particular condition:



回答3:

XSLT isn't a procedural language; don't think of for-each as being a "loop" in the way you have a loop in Java. For-each is a way to apply a template to each of a bunch of items. It doesn't necessarily happen in a particular order, so you can't think of it as "apply this template to each of a bunch of items until such-and-such happens, then stop".

That said, you can use the select attribute to filter the results, so it becomes more like "apply a template to each of a bunch of items, but only if such-and-such is true of them".

If what you really want is "apply a template to each of a bunch of items, where such-and-such is true of them, but only to the first one this is true of", you can combine the select attribute with the position() function.



回答4:

A "break" from the body of an XSLT instruction cannot be specified using a syntactic construct, however it can be simulated.

This code snippet at topxml.com describes the technique in detail:

In case you need a ""break"" from an xsl:for-each loop

Essentially two techniques are discussed:

  1. Performing something inside the body of only if a specific condition is satisfied.

  2. Specifying the processing not using but with recursion

The second method has the benefit of being able to perform the exit immediately, contrasted with the first method having to still perform many "empty cycles" even after the exit-condition has been satisfied.



回答5:

Hello I kwow this is an old post but maybe it can help other developers. I have found a way to break a for each in XSLT it is not litteraly a break but if you see the code you will get it. As you know or not know you can use inline C# code in xslt. In this example i want to loop al the nodes and take the first NTE node with Value RC But if I get a node that differs from the NTE node i want to stop looking at the condition. So I set a global variable in C# code and I ask the value each time I go through a node:

           .....      


回答6:

I had a similar situation and here is the code I had written. For logical reasons, I couldn't fit in the other conditions with condition01.

 --body of for loop  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!