A common requirement for an XML based application is the ability to do some form of simple string building. For example, the following query outputs a set of elements whose values are built up as a string, depending on some other value that is passed is as part of an iteration:
declare @x xml
set @x=``
select @x.query(`
for $index in (1, 2, 3)
return
{ "Item" }{ $index }
`)
The result of this query is the following set of 3 nodes:
Item1
Item2
Item3
In this instance, we constructed the string value for the element by creating 2 separate text nodes - one containing the string literal "Item" and the other containing the iterator value. As part of XML serialization, consecutive text nodes in the XML infoset are merged into a single text node, thus providing us with our desired output. Alternatively, we could have used the XQuery concat() function:
declare @x xml
set @x=``
select @x.query(`
for $index in (1, 2, 3)
return
{ concat( "Item", $index cast as xs:string ) }
`)
Notice that we had to add an explicit cast to the iterator value since the concat() function will only accept string values as it`s arguments.
A further option would be to build your string value as a sequence of atomic values:
declare @x xml
set @x=``
select @x.query(`
for $index in (1, 2, 3)
return
{ ( "Item", $index ) }
`)
But, there is a subtle difference in the output of this query which is as follows:
Item 1
Item 2
Item 3
Notice that there is a space between the "Item" string value and the iterator value. Sequences of items are serialized with a space between each of the entries!
So, if you need to build strings - use the concat() function explicitly or rely on the XML infoset serialization rules and build multiple, consecutive text nodes. Remember that sequences are serialized with a space between each item.
-
Disclaimer:
This posting is provided AS IS with no waranties, and confers no rights.
Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm.