XSLT - What XPath Is

1. What XPath Is

  • Full form: XPath = XML Path Language.

  • Purpose: A language to locate, navigate, and select nodes in an XML document.

  • Nodes: XPath works with different types of nodes in XML:

    • Element nodes (<book>)

    • Attribute nodes (@id)

    • Text nodes (1984)

    • Root node (/)

    • Comment nodes and processing instructions

  • Key idea: XPath is like giving an address or path to a piece of data inside an XML document.


2. Basic XPath Syntax

XPath Meaning
/ Root node
/library/book <book> elements directly under <library>
//book All <book> elements anywhere in the document
book/title <title> child elements of <book>
@id Attribute id of the current node
text() Text inside an element
* Any element node
@* Any attribute node

3. Role of XPath in XSLT

XPath is heavily used in XSLT for:

  1. Template matching

    <xsl:template match="book/title"/>
    
    • The match attribute uses XPath to select which nodes the template applies to.

  2. Selecting nodes inside templates

    <xsl:value-of select="title"/>
    <xsl:apply-templates select="book"/>
    
    • The select attribute uses XPath to pick nodes for output or further processing.

  3. Filtering and conditions

    <xsl:if test="price > 20"/>
    <xsl:for-each select="book[author='George Orwell']"/>
    
    • XPath expressions are used for conditions, loops, and filtering nodes.


4. Example

XML:

<library>
  <book id="b1">
    <title>1984</title>
    <author>George Orwell</author>
    <price>15</price>
  </book>
  <book id="b2">
    <title>Brave New World</title>
    <author>Aldous Huxley</author>
    <price>20</price>
  </book>
</library>

XSLT using XPath:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  
  <!-- Root template -->
  <xsl:template match="/">
    <ul>
      <xsl:apply-templates select="library/book[price>15]"/>
    </ul>
  </xsl:template>
  
  <!-- Template for <book> -->
  <xsl:template match="book">
    <li>
      <xsl:value-of select="title"/> by <xsl:value-of select="author"/>
    </li>
  </xsl:template>
  
</xsl:stylesheet>

Output:

<ul>
  <li>Brave New World by Aldous Huxley</li>
</ul>

Explanation:

  • library/book[price>15] → XPath selects only books with price > 15.

  • title and author inside <book> are selected using XPath.


5. Summary of XPath Role in XSLT

  1. Node selection: Picks the elements, attributes, or text to transform.

  2. Template matching: Determines which <xsl:template> applies to which XML nodes.

  3. Filtering & conditions: Helps apply transformations only to specific nodes.

  4. Navigation: Allows moving up, down, or sideways in the XML tree.

In short: XPath is the “GPS” inside XML that XSLT uses to locate and process data accurately.