Wildcards

XPATH WildcardsXPATH allows the use of wildcards to write more robust path expressions where the use of specific path expressions is either impossible or undesirable.

XPATH supports the following wildcards:

Wildcard/FunctionDescription
*matches any element node.
@*matches any attribute node.
node()matches any type of node.

The wildcard is used in place of the literal name of a node.

Examples

The examples use the library XML document as a reference. 

   1: <?xml version="1.0" encoding="UTF-8"?>

   2: <library>

   3:     <category name="dogs">

   4:         <book>

   5:             <title lang="english">All about dogs</title>

   6:             <author>Someone</author>

   7:             <isin>true</isin>

   8:             <daysuntilreturn>0</daysuntilreturn>

   9:             <price>15.10</price>

  10:         </book>

  11:     </category>

  12:      <category name="cats">

  13:         <book>

  14:             <title lang="english">All about cats</title>

  15:             <author>Someone</author>

  16:             <isin>false</isin>

  17:             <daysuntilreturn>3</daysuntilreturn>

  18:             <price>12.00</price>

  19:         </book>

  20:         <book>

  21:             <title lang="zulu">Konke mayelana ikati</title>

  22:             <author>Else</author>

  23:             <isin>true</isin>

  24:             <daysuntilreturn>0</daysuntilreturn>

  25:             <price>25.99</price>

  26:         </book>

  27:     </category>

  28: </library>

 

Example: Match All Nodes

   1: //*

  1. Matches ALL nodes in the input XML document.

Example: Match All Categories

   1: /library/*

   2: /*/category

  1. Matches all child nodes of library – in this example the only child nodes are category.
  2. Matches all category nodes as children of the root node (library). If there are nodes other than category under the library node then this expression will only return the required category nodes.

Example: Match All Books

   1: /library/category/*

   2: /*/*/book

  1. Matches all children under the category node. In our example XML the only children are the book nodes.
  2. Matches all book nodes located at that level in our XML hierarchy.

Example: Match All Elements With An Attribute

   1: //*[@*]

   2: //title[@*]

  1. Matches ANY element node which has an attribute defined. This example will only match category and title nodes.
  2. Matches only title element nodes with an attribute defined.

Posted in XPATH and tagged .

Leave a Reply