How to ask the `n`-th XPath result with `xmlstarlet select`?
Feb 17, 11:21pm

To select the n-th XPath result using xmlstarlet select, you can use predicates in your XPath expression. The syntax is straightforward:

Basic Syntax

bash
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):

xml
<books> <book>Book 1</book> <book>Book 2</book> <book>Book 3</book> </books>

To select the 2nd <book> element, use:

bash
xmlstarlet select -t -v "//book[position()=2]" -n books.xml

Output:

Book 2

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.
Feb 17, 11:21pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

<books> <book>Book 1</book> <book>Book 2</book> <book>Book 3</book> </books>