Concept
XPath is a W3C standard, specially designed for navigating and locating nodes within XML documents and serves as the core foundation of XSLT. All expressions inside select="" and test="" in XSLT use XPath.
- Locate nodes via path expressions
- Over 100 built‑in standard functions: string operations, numeric calculations, date comparison, node manipulation, logical operations, etc.
7 Node Types
Document node (root node), element node, attribute node, text node, comment node, processing instruction node, namespace node.
Example:
<title lang="eng">Harry Potter</title>
<title>→ Element nodelang="eng"→ Attribute nodeHarry Potter→ Text node
Concept
- Atomic value: Node content without children or parent nodes, e.g.
eng,29.99 - Item: Item = Node or atomic value
Relationships Between XML Nodes
Take <bookstore><book><title></title></book></bookstore> as an example
- Parent: Every element and attribute has exactly one parent;
bookis the parent oftitle - Children: An element can have multiple child nodes;
titleandpriceare children ofbook - Sibling: Nodes sharing the same parent node; title and price at the same level are siblings to each other
- Ancestor: Parent, parent’s parent and all higher‑level nodes upwards; ancestors of
titleare book and bookstore
Path Expressions
Select XML nodes by paths and steps
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
</bookstore>Code language: HTML, XML (xml)
| Expression | Meaning |
|---|---|
bookstore | Select the bookstore element under root |
/bookstore | Absolute path, match starting from root node |
bookstore/book | Select all book child‑elements under bookstore |
//book | book elements anywhere in the document (global search) |
//@lang | Select all attribute nodes named lang |
XPath Function:position()
<xsl:value-of select="position()" />Code language: HTML, XML (xml)
position() is a built‑in XPath function that gets the sequence number of current iterated node within node‑set, counting starts from 1.
Example: Output sequence numbers
<?xml version="1.0" encoding="gb2312"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head></head>
<body>
<ul>
<!--Iterate over all students class/student -->
<xsl:for-each select="class/student">
<xsl:sort select="age"/> <!--Sort by age ascending-->
<!--Filter students whose height >160-->
<xsl:if test="height > 160">
<li>
<xsl:value-of select="position()" />、<!--Output serial number-->
<xsl:value-of select="name"/>;
<!--Multiple condition judgment-->
<xsl:choose>
<xsl:when test="height > 200">
<b><xsl:value-of select="age"/></b>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="age"/>
</xsl:otherwise>
</xsl:choose>
</li>
</xsl:if>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>Code language: HTML, XML (xml)
XPath
Previous: Multi‑branch