Select a range of nodes in an XML file using an XPath query
In the following example we can see how to use the position() selector in a XPath query to select a nodes range.
Consider the following XML:
<?xml version="1.0" encoding="utf-8" ?> <Data> <Books> <book> <name>Book 1</name> <price>10</price> </book> <book> <name>Book 2</name> <price>81</price> </book> <book> <name>Book 3</name> <price>58</price> </book> <book> <name>Book 4</name> <price>43</price> </book> <book> <name>Book 5</name> <price>54</price> </book> <book> <name>Book 6</name> <price>22</price> </book> </Books> </Data>
Suppose to select the nodes “book” in the range 2-4. The XPath query is the following:
//book[position() >= 2 and position() <= 4]
Nell’esempio seguente vediamo come utilizzare il selettore position() in una query XPath per selezionare un intervallo di nodi.
Consideriamo il seguente XML:
<?xml version="1.0" encoding="utf-8" ?> <Data> <Books> <book> <name>Book 1</name> <price>10</price> </book> <book> <name>Book 2</name> <price>81</price> </book> <book> <name>Book 3</name> <price>58</price> </book> <book> <name>Book 4</name> <price>43</price> </book> <book> <name>Book 5</name> <price>54</price> </book> <book> <name>Book 6</name> <price>22</price> </book> </Books> </Data>
Supponiamo di voler selezionare i nodi “book” nell’intervallo 2-4, cioè selezionare i nodi relativi ai libri 2,3 e 4. La query XPath da utilizzare è la seguente:
//book[position() >= 2 and position() <= 4]
Lascia un commento