XQuery Sequences
Last Updated :
09 Oct, 2023
The XQuery subsequence function returns a contiguous sequence of items from a given sequence, starting at a specified position and continuing for a specified number of items.
The subsequence function has two or three arguments:
- $sourceSeq: The sequence from which to extract the subsequence.
- $startingLoc: The index of the first item in the subsequence. The index starts at 1.
- $length: The number of items in the subsequence. This argument is optional. If it is omitted, the function will return the entire subsequence from $startingLoc to the end of $sourceSeq.
Here are examples of using the subsequence function:
Example 1: Get a subsequence of all subchild1 elements
XML
< root >
< child1 >
< subchild1 >1</ subchild1 >
< subchild2 >2</ subchild2 >
</ child1 >
< child2 >
< subchild1 >3</ subchild1 >
< subchild2 >4</ subchild2 >
</ child2 >
</ root >
|
XML
< xsl:template match = "/" >
< xsl:variable name = "subchild1_subsequence" >
< xsl:for-each select = "//subchild1" >
< xsl:copy-of select = "." />
</ xsl:for-each >
</ xsl:variable >
< xsl:for-each select = "$subchild1_subsequence" >
< xsl:value-of select = "." />
</ xsl:for-each >
</ xsl:template >
</ xsl:stylesheet >
|
Output:
1
3
Example 2: Get a subsequence of the first two subchild1 elements
XML
< root >
< child1 >
< subchild1 >1</ subchild1 >
< subchild2 >2</ subchild2 >
</ child1 >
< child2 >
< subchild1 >3</ subchild1 >
< subchild2 >4</ subchild2 >
</ child2 >
</ root >
|
XML
< xsl:template match = "/" >
< xsl:variable name = "subchild1_subsequence" >
< xsl:for-each select = "//subchild1[position() <= 2]" >
< xsl:copy-of select = "." />
</ xsl:for-each >
</ xsl:variable >
< xsl:for-each select = "$subchild1_subsequence" >
< xsl:value-of select = "." />
</ xsl:for-each >
</ xsl:template >
</ xsl:stylesheet >
|
Output:
1
3
Conclusion:
The XQuery subsequence function is a powerful tool for extracting subsets of data from sequences. It can be used to implement a variety of tasks, such as filtering, sorting, and grouping data.
Share your thoughts in the comments
Please Login to comment...