Conditions and loops

If/Else

XSharper has the usual if/else construction, which has two notations.

The first XML-like notation, where else is included as a part of if element is a bit cumbersome. There is however an alternative syntax, with , yet there is no way to validate it against XSD schema.

<set a='Z' />
<set b='X' />
<if isTrue="${=$a>$b}">
		<print>${a} is more than ${b}</print>
	<else>
		<print>${a} is NOT more than ${b}</print>
	</else>
</if>

<!-- alternative syntax -->
<if isTrue="${=$b>$a}">
		<print>${b} is more than ${a}</print>
<else />
		<print>${b} is NOT more than ${a}</print>
</if>

There is a bunch of possible attributes in conditionals, isTrue, isFalse, isSet (if variable is set), isNotSet, isZero, isNotZero etc. Use xsharper /? if for more details.

While loop

XSharper has only a simple while loop.

<xsharper>
	<set i="0" />
	<while isTrue="${= $i #LT# 5 }">
		<print>i=${i}</print>
		<set i="${=(int)$i+1}" />
	</while>
</xsharper>

Note the use of #lt# instead of &lt;, to make the expression more readable.

While loop may define a maximum number of loops:

<xsharper>
	<set i="0" />
	<while maxLoops="3">
		<print>i=${i}</print>
		<set i="${=(int)$i+1}" />
	</while>
</xsharper>

Actually, while can automatically assign its loop counter value to a variable specified in name attribute, making the code a bit shorter:

<while name="i" maxLoops="3" >
	<print>i=${i}</print>
</while>

There is also a break statement, to exit a loop prematurely:

<xsharper>
	<set i="0" />
	<while>
		<print>i=${i}</print>
		<set i="${=(int)$i+1}" />
		<if isTrue="${= $i > 10}">
			<break />
		</if>
	</while>
</xsharper>

ForEach loop

forEach loop iterates through each element of a collection, XML document or a rowset.

Syntax is <foreach variable='${enumerable}'>

<!-- print 1,2,3 in different rows -->
<foreach x="${= {1,2,3}}" >
	<print>${x}</print>
</foreach>

Or <foreach name='x' in='${enumerable}'> where name is optional (and defaults to empty string):

<!-- print list of files in C:\ -->
<foreach in="${= new DirectoryInfo('c:\').GetFileSystemInfos('*.*') }" >
	<print>${=$.FullName}</print>
</foreach>

foreach can also parse rowsets:

	<!-- running a piece of code for every row of rowset -->
	<rowset id="rs">
		<row order="1" description="Two large pineapple pizzas" />
		<row order="22" description="One Greek Salad" />
	</rowset>
	
	<foreach rowsetId="rs" name="pref_">
		<print>Order: ${=$pref_order.PadLeft(5)}</print>
		<print>Description=${pref_description}</print>
		<print>-----</print>
	</foreach>