xslt - How can I change the order of an xsl for-each? -
I need to change the order in which each of me is executed, if some conditions are met.
Here looks like my XML:
& lt; OptionList & gt; & Lt; Option name = "my first option" /> & Lt; Option name = "my second option" /> & Lt; / OptionList & gt;
However, in some cases, my XML may be like this:
& lt; OptionList & gt; & Lt; Option / & gt; & Lt; Option name = "my second option" /> & Lt; / OptionList & gt;
In my XSL, I am doing this for each:
& lt; Xsl: each selection = "// options list / options" & gt; {...} & lt; / Xsl: each -G & gt;
I know that I can change the order of option node by using this line for each:
The problem is that I want my order to be removed only when my first audience node is empty and its name is not attribute otherwise I want to keep the default ascending order.
How can I get this? So far, whatever I tried, it ended with the "unearthing gap" or the invalid use of the xpath function.
You can use a hack to change sort order based on the condition:
& lt ;? Xml version = "1.0" encoding = "UTF-8"? & Gt; & Lt; Xsl: stylesheet version = "1.0" xmlns: xsl = "http://www.w3.org/1999/XSL/transform" & gt; & Lt; Xsl: output method = "xml" indent = "yes" /> & Lt; Xsl: template match = "/" & gt; & Lt; Results & gt; & Lt; Xsl: each selection = "// options list / options" & gt; & Lt; Xsl: Select sort data-type = "number" order = "ascending" = "position () * (- 2 * number (not (// option list / option [1] / @name)) + 1" Gt; & lt; Option & gt; & lt; xsl: Select Value = "@ name" /> for LS; & gt; ; / Results & gt; & lt; / XSL: template & gt; & lt; / XSL: stylesheet & gt;
The hack is that if there is a number ((true) ) Returns
1 and number (wrong) returns 0. result, expression
-2 * number (not (// options list / Option [1] / @name)) + 1
1
evaluates name
attribute in the first option
element and -1
is otherwise. This is used as a factor in sort order reversal.
Comments
Post a Comment