To select the n-th XPath result using xmlstarlet select, you can use predicates in your XPath expression. The syntax is straightforward:
Basic Syntax
xmlstarlet select -t -v "xpath_expression[position()=n]" -n file.xml
position()=n filters the result to only the n-th node.
-t sets the output template.
-v specifies the value to output.
-n adds a newline after each result.
Example
Suppose you have the following XML (books.xml):
<books>
<book>Book 1</book>
<book>Book 2</book>
<book>Book 3</book>
</books>
To select the 2nd <book> element, use:
xmlstarlet select -t -v "//book[position()=2]" -n books.xml
Output:
Notes
- If you want the last element, use
position()=last().
- If you want a range (e.g., 2nd to 4th), use
position() >= 2 and position() <= 4.