Open In App

XQuery Sequences

Last Updated : 09 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




<!--index.xml-->
  
<root>
  <child1>
    <subchild1>1</subchild1>
    <subchild2>2</subchild2>
  </child1>
  <child2>
    <subchild1>3</subchild1>
    <subchild2>4</subchild2>
  </child2>
</root>


XML




<!--stylesheet-->
  
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <!-- Get the subsequence of all subchild1 elements -->
  <xsl:variable name="subchild1_subsequence">
    <xsl:for-each select="//subchild1">
      <xsl:copy-of select="."/>
    </xsl:for-each>
  </xsl:variable>
  <!-- Print the subsequence -->
  <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




<!--index.xml-->
  
<root>
  <child1>
    <subchild1>1</subchild1>
    <subchild2>2</subchild2>
  </child1>
  <child2>
    <subchild1>3</subchild1>
    <subchild2>4</subchild2>
  </child2>
</root>


XML




<!--stylesheet-->
  
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <!-- Get the subsequence of the first two subchild1 elements -->
  <xsl:variable name="subchild1_subsequence">
    <xsl:for-each select="//subchild1[position() <= 2]">
      <xsl:copy-of select="."/>
    </xsl:for-each>
  </xsl:variable>
  <!-- Print the subsequence -->
  <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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads