Xpath 简明教程

XPath - Quick Guide

XPath - Overview

在学习 XPath 前,我们应该首先理解 XSL(即 *E*xtensible *S*tylesheet *L*anguage)。它与 XML 的关系类似于 CSS 与 HTML 的关系。

Before learning XPath, we should first understand XSL which stands for *E*xtensible *S*tylesheet *L*anguage. It is similar to XML as CSS is to HTML.

Need for XSL

对于 HTML 文档,标签(例如 table、div、span 等)是预定义的。浏览器知道如何使用 CSS 样式向其添加样式并显示它们。但对于 XML 文档,标签是未预定义的。为了理解和设置 XML 文档的样式, World Wide Web Consortium (W3C) 开发了 XSL,它可以用作基于 XML 的样式表语言。XSL 文档指定浏览器应如何呈现 XML 文档。

In case of HTML documents, tags are predefined such as table, div, span, etc. The browser knows how to add style to them and display them using CSS styles. But in case of XML documents, tags are not predefined. In order to understand and style an XML document, World Wide Web Consortium (W3C) developed XSL which can act as an XML-based Stylesheet Language. An XSL document specifies how a browser should render an XML document.

以下是 XSL 的主要部分 −

Following are the main parts of XSL −

  1. XSLT − used to transform XML documents into various other types of document.

  2. XPath − used to navigate XML documents.

  3. XSL-FO − used to format XML documents.

What is XPath?

XPath 是万维网联盟 (W3C) 的官方推荐。它定义了一种在 XML 文件中查找信息的语言。它用于遍历 XML 文档的元素和属性。XPath 提供了多种类型的表达式,可用于从 XML 文档中查询相关信息。

XPath is an official recommendation of the World Wide Web Consortium (W3C). It defines a language to find information in an XML file. It is used to traverse elements and attributes of an XML document. XPath provides various types of expressions which can be used to enquire relevant information from the XML document.

  1. Structure Definitions − XPath defines the parts of an XML document like element, attribute, text, namespace, processing-instruction, comment, and document nodes

  2. Path Expressions − XPath provides powerful path expressions select nodes or list of nodes in XML documents.

  3. Standard Functions − XPath provides a rich library of standard functions for manipulation of string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values etc.

  4. Major part of XSLT − XPath is one of the major elements in XSLT standard and is must have knowledge in order to work with XSLT documents.

  5. W3C recommendation − XPath is an official recommendation of World Wide Web Consortium (W3C).

在使用 XPath 时,应谨记以下几点 −

One should keep the following points in mind, while working with XPath −

  1. XPath is core component of XSLT standard.

  2. XSLT cannot work without XPath.

  3. XPath is basis of XQuery and XPointer.

XPath - Expression

XPath 表达式通常定义一个模式,以便选择一组节点。XSLT 使用这些模式来执行转换,XPointer 使用这些模式来寻址。

An XPath expression generally defines a pattern in order to select a set of nodes. These patterns are used by XSLT to perform transformations or by XPointer for addressing purpose.

XPath 规范指定了七种类型的节点,它们可以是 XPath 表达式执行的输出。

XPath specification specifies seven types of nodes which can be the output of execution of the XPath expression.

  1. Root

  2. Element

  3. Text

  4. Attribute

  5. Comment

  6. Processing Instruction

  7. Namespace

XPath 使用路径表达式从 XML 文档中选择节点或节点列表。

XPath uses a path expression to select node or a list of nodes from an XML document.

以下是用于从 XML 文档中选择任何节点/节点列表的有用路径和表达式的列表。

Following is the list of useful paths and expression to select any node/ list of nodes from an XML document.

S.No.

Expression & Description

1

node-name Select all nodes with the given name "nodename"

2

/ Selection starts from the root node

3

// Selection starts from the current node that match the selection

4

. Selects the current node

5

.. Selects the parent of the current node

6

@ Selects attributes

7

student Example − Selects all nodes with the name "student"

8

class/student Example − Selects all student elements that are children of class

9

//student Selects all student elements no matter where they are in the document

Example

在此示例中,我们创建了一个示例 XML 文档 students.xml 及其样式表文档 students.xsl ,该文档使用 XPath 表达式在各种 XSL 标记的 select 属性下,获取每个 student 节点的学号、first name、last name、nickname 和成绩的值。

In this example, we’ve created a sample XML document, students.xml and its stylesheet document students.xsl which uses the XPath expressions under select attribute of various XSL tags to get the values of roll no, firstname, lastname, nickname and marks of each student node.

students.xml

<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
   <student rollno = "393">
      <firstname>Dinkar</firstname>
      <lastname>Kad</lastname>
      <nickname>Dinkar</nickname>
      <marks>85</marks>
   </student>
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>Vinni</nickname>
      <marks>95</marks>
   </student>
   <student rollno = "593">
      <firstname>Jasvir</firstname>
      <lastname>Singh</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>

students.xsl

<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

   <xsl:template match = "/">
      <html>
         <body>
            <h2>Students</h2>
            <table border = "1">
               <tr bgcolor = "#9acd32">
                  <th>Roll No</th>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Nick Name</th>
                  <th>Marks</th>
               </tr>
               <xsl:for-each select = "class/student">
                  <tr>
                     <td> <xsl:value-of select = "@rollno"/></td>
                     <td><xsl:value-of select = "firstname"/></td>
                     <td><xsl:value-of select = "lastname"/></td>
                     <td><xsl:value-of select = "nickname"/></td>
                     <td><xsl:value-of select = "marks"/></td>
                  </tr>
               </xsl:for-each>
            </table>
         </body>
      </html>
   </xsl:template>

</xsl:stylesheet>

Verify the output

xpath students

XPath - Nodes

在本章中,我们将详细了解 XPath 表达式,涵盖 XPath 定义和处理的常见类型节点。

In this chapter, we’ll see the XPath expression in details covering common types of Nodes, XPath defines and handles.

S.No.

Node Type & Description

1

RootRoot element node of an XML Document.

2

ElementElement node.

3

TextText of an element node.

4

AttributeAttribute of an element node.

5

CommentComment

XPath - Absolute Path

位置路径指定 XML 文档中节点的位置。此路径可以是绝对路径或相对路径。如果位置路径以根节点或 “/” 开头,则它是一个绝对路径。以下是使用绝对路径定位元素的一些示例。

Location path specifies the location of node in XML document. This path can be absolute or relative. If location path starts with root node or with '/' then it is an absolute path. Following are few of the example locating the elements using absolute path.

/class/student − 选择班级根节点中的学生节点。

/class/student − select student nodes within class root node.

<xsl:for-each select = "/class/student">

/class/student/firstname − 选择班级根节点中某个学生节点的 firstName。

/class/student/firstname − select firstname of a student node within class root node.

<p><xsl:value-of select = "/class/student/firstname"/></p>

Example

在此示例中,我们创建了一个 XML 文档示例 students.xml 和使用 XPath 表达式的样式表文档 students.xsl

In this example, we’ve created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions.

下面是使用的 XML 示例。

Following is the sample XML used.

students.xml

<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
   <student rollno = "393">
      <firstname>Dinkar</firstname>
      <lastname>Kad</lastname>
      <nickname>Dinkar</nickname>
      <marks>85</marks>
   </student>
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>Vinni</nickname>
      <marks>95</marks>
   </student>
   <student rollno = "593">
      <firstname>Jasvir</firstname>
      <lastname>Singh</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>

students.xsl

<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

   <xsl:template match = "/" >
      <html>
         <body>
            <h3>Details of each Students. </h3>
            <table border = "1">
               <tr bgcolor = "#9acd32">
                  <th>Roll No</th>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Nick Name</th>
                  <th>Marks</th>
               </tr>

               <tr>
                  <td><xsl:value-of select = "/class/student[1]/@rollno"/></td>
                  <td><xsl:value-of select = "/class/student[1]/firstname"/></td>
                  <td><xsl:value-of select = "/class/student[1]/lastname"/></td>
                  <td><xsl:value-of select = "/class/student[1]/nickname"/></td>
                  <td><xsl:value-of select = "/class/student[1]/marks"/></td>
               </tr>

               <tr>
                  <td>
                     <xsl:value-of select = "/class/student/@rollno"/>
                  </td>
                  <td><xsl:value-of select = "/class/student[2]/firstname"/></td>
                  <td><xsl:value-of select = "/class/student[2]/lastname"/></td>
                  <td><xsl:value-of select = "/class/student[2]/nickname"/></td>
                  <td><xsl:value-of select = "/class/student[2]/marks"/></td>
               </tr>

               <tr>
                  <td>
                     <xsl:value-of select = "/class/student[3]/@rollno"/>
                  </td>
                  <td><xsl:value-of select = "/class/student[3]/firstname"/></td>
                  <td><xsl:value-of select = "/class/student[3]/lastname"/></td>
                  <td><xsl:value-of select = "/class/student[3]/nickname"/></td>
                  <td><xsl:value-of select = "/class/student[3]/marks"/></td>
               </tr>

            </table>

         </body>
      </html>
   </xsl:template>
</xsl:stylesheet>

Verify the output

xpath students

XPath - Relative Path

位置路径指定 XML 文档中节点的位置。此路径可以是绝对路径或相对路径。如果位置路径以我们选择的节点开头,则它是一个相对路径。

Location path specifies the location of node in XML document. This path can be absolute or relative. If location path starts with the node that we’ve selected then it is a relative path.

以下是使用相对路径定位元素的一些示例。

Following are few examples locating the elements using relative path.

firstname − 选择与学生节点相关的 firstName。

firstname − select firstname related to student nodes.

<p><xsl:value-of select = "firstname"/></p>

Example

在此示例中,我们创建了一个 XML 文档示例 students.xml 和使用 XPath 表达式的样式表文档 students.xsl

In this example, we’ve created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions.

下面是使用的 XML 示例。

Following is the sample XML used.

students.xml

<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
   <student rollno = "393">
      <firstname>Dinkar</firstname>
      <lastname>Kad</lastname>
      <nickname>Dinkar</nickname>
      <marks>85</marks>
   </student>
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>Vinni</nickname>
      <marks>95</marks>
   </student>
   <student rollno = "593">
      <firstname>Jasvir</firstname>
      <lastname>Singh</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>

students.xsl

<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

   <xsl:template match = "/" >
      <html>
         <body>
            <h3>Details of each Students. </h3>
            <table border = "1">
               <tr bgcolor = "#9acd32">
                  <th>Roll No</th>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Nick Name</th>
                  <th>Marks</th>
               </tr>

               <xsl:for-each select = "/class/student">
                  <tr>
                     <td><xsl:value-of select = "@rollno"/></td>
                     <td><xsl:value-of select = "firstname"/></td>
                     <td><xsl:value-of select = "lastname"/></td>
                     <td><xsl:value-of select = "nickname"/></td>
                     <td><xsl:value-of select = "marks"/></td>
                  </tr>
               </xsl:for-each>
            </table>
         </body>
      </html>
   </xsl:template>
</xsl:stylesheet>

Verify the output

xpath students

XPath - Axes

由于位置路径使用绝对或相对路径定义节点的位置,因此轴用于按其关系(如 parent, child, sibling, 等)识别元素。之所以这样命名轴,是因为它们引用元素相对于某个元素所在的轴。

As location path defines the location of a node using absolute or relative path, axes are used to identify elements by their relationship like parent, child, sibling, etc. Axes are named so because they refer to axis on which elements are lying relative to an element.

以下是各种轴值的列表。

Following is the list of various Axis values.

S.No.

Axis & Description

1

ancestor Represents the ancestors of the current node which include the parents up to the root node.

2

ancestor-or-self Represents the current node and it’s ancestors.

3

attribute Represents the attributes of the current node.

4

child Represents the children of the current node.

5

descendant Represents the descendants of the current node. Descendants include the node’s children upto the leaf node(no more children).

6

descendant-or-self Represents the current node and it’s descendants.

7

following Represents all nodes that come after the current node.

8

following-sibling Represents the following siblings of the context node. Siblings are at the same level as the current node and share it’s parent.

9

namespace Represents the namespace of the current node.

10

parent Represents the parent of the current node.

11

preceding Represents all nodes that come before the current node (i.e. before it’s opening tag).

12

self Represents the current node.

以下是轴使用的一些示例。

Following are a few examples on the uses of axes.

firstname − 选择与学生节点相关的 firstName。

firstname − select firstname related to student nodes.

<p><xsl:value-of select = "firstname"/></p>
<xsl:value-of select = "/class/student/preceding-sibling::comment()"/>

Example

在此示例中,我们创建了一个 XML 文档示例 students.xml 和使用 XPath 表达式的样式表文档 students.xsl

In this example, we’ve created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions.

下面是使用的 XML 示例。

Following is the sample XML used.

students.xml

<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
   <!-- Comment: This is a list of student -->
   <student rollno = "393">
      <firstname>Dinkar</firstname>
      <lastname>Kad</lastname>
      <nickname>Dinkar</nickname>
      <marks>85</marks>
   </student>
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>Vinni</nickname>
      <marks>95</marks>
   </student>
   <student rollno = "593">
      <firstname>Jasvir</firstname>
      <lastname>Singh</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>

students.xsl

<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

   <xsl:template match = "/" >
      <html>
         <body>
            <xsl:value-of select = "/class/student/preceding-sibling::comment()"/>
            <br/>
            <xsl:text>First Student: </xsl:text>
            <xsl:value-of select = "/class/student/child::firstname" />
         </body>
      </html>
   </xsl:template>
</xsl:stylesheet>

Verify the output

xpath axes

XPath - Operators

在本章中,我们将详细了解 XPath 运算符和函数,包括常用的 XPath defineshandles 。XPath 定义了对节点、字符串、数字和布尔类型的运算符和函数。

In this chapter, we’ll see XPath operators and functions in details covering commonly used XPath defines and handles. XPath defines Operators and functions on Nodes, String, Number and Boolean types.

以下是我们将要讨论的列表。

Following is the list we are going to discuss about.

S.No.

Operators/Functions & Description

1

Comparision OperatorsComparision operators to compare values.

2

Boolean OperatorsBoolean operators to check 'and', 'or' & 'not' functionalities.

3

Number Functions/OperatorsOperators/Functions on numbers.

4

String FunctionsVarious string functions.

5

Node Functions/OperatorsVarious functions and operators acting on nodes.

XPath - Wildcard

XPath 定义了以下节点通配符,可与 XPath 表达式配合使用。

XPath defines the following wildcards on nodes to be used with the XPath expressions.

S.No.

WildCard & Description

1

* used to match any node.

2

. used to match the current node in context.

3

@* used to match any attribute

4

node() used to match node of any type

Example

此示例通过遍历每个学生,创建一个带有其详细信息的 <student> 元素表。

This example creates a table of <student> element with their details, by iterating over each student.

students.xml

<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
   <student rollno = "393">
      <firstname>Dinkar</firstname>
      <lastname>Kad</lastname>
      <nickname>Dinkar</nickname>
      <marks>85</marks>
   </student>
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>Vinni</nickname>
      <marks>95</marks>
   </student>
   <student rollno = "593">
      <firstname>Jasvir</firstname>
      <lastname>Singh</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>

students.xsl

<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

   <xsl:template match = "/">
      <html>
         <body>
            <h2>Students</h2>
            <xsl:apply-templates select = "class/*" />
         </body>
      </html>
   </xsl:template>

   <xsl:template match = "class/*">
      <xsl:apply-templates select = "@rollno" />
      <xsl:apply-templates select = "firstname" />
      <xsl:apply-templates select = "lastname" />
      <xsl:apply-templates select = "nickname" />
      <xsl:apply-templates select = "marks" />
      <br />
   </xsl:template>

   <xsl:template match = "@rollno">
      <span style = "font-size = 22px;">
         <xsl:value-of select = "." />
      </span>
      <br />
   </xsl:template>

   <xsl:template match = "firstname">
      First Name:<span style = "color:blue;">
         <xsl:value-of select = "." />
      </span>
      <br />
   </xsl:template>

   <xsl:template match = "lastname">
      Last Name:<span style = "color:green;">
         <xsl:value-of select = "." />
      </span>
      <br />
   </xsl:template>

   <xsl:template match = "nickname">
      Nick Name:<span style = "color:red;">
         <xsl:value-of select = "." />
      </span>
      <br />
   </xsl:template>

   <xsl:template match = "marks">
      Marks:<span style = "color:gray;">
         <xsl:value-of select = "." />
      </span>
      <br />
   </xsl:template>

</xsl:stylesheet>

Verify the output

xpath students wildcard

XPath - Predicate

谓词是指用方括号编写的 XPath 表达式。它用于限制节点集中符合某些条件的所选节点。例如,

Predicate refers to the XPath expression written in square brackets. It refers to restrict the selected nodes in a node set for some condition. For example,

S.No.

Predicate & Description

1

/class/student[1] Select first student element which is child of the class element.

2

/class/student[last()] Select last student element which is child of the class element.

3

/class/student[@rolllno = 493] Select student element with rollno 493.

4

/class/student[marks>85] Select student element with marks > 85.

Example

此示例通过遍历每个学生,创建一个带有其详细信息的 <student> 元素表。它计算了该学生节点的位置,然后打印了学生的详细信息以及序号。

This example creates a table of <student> element with their details, by iterating over each student. It calculates the position of the student node and then prints the student(s) details along with serial no.

students.xml

<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
   <student rollno = "393">
      <firstname>Dinkar</firstname>
      <lastname>Kad</lastname>
      <nickname>Dinkar</nickname>
      <marks>85</marks>
   </student>
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>Vinni</nickname>
      <marks>95</marks>
   </student>
   <student rollno = "593">
      <firstname>Jasvir</firstname>
      <lastname>Singh</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>

students.xsl

<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

   <xsl:template match = "/">
      <html>
         <body>
            <h2>Students</h2>
            <table border = "1">
               <tr bgcolor = "#9acd32">
                  <th>Roll No</th>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Nick Name</th>
                  <th>Marks</th>
               </tr>

               <xsl:for-each select = "/class/student[1]">
                  <tr>
                     <td><xsl:value-of select = "@rollno"/></td>
                     <td><xsl:value-of select = "firstname"/></td>
                     <td><xsl:value-of select = "lastname"/></td>
                     <td><xsl:value-of select = "nickname"/></td>
                     <td><xsl:value-of select = "marks"/></td>
                  </tr>
               </xsl:for-each>

               <xsl:for-each select = "/class/student[last()]">
                  <tr>
                     <td><xsl:value-of select = "@rollno"/></td>
                     <td><xsl:value-of select = "firstname"/></td>
                     <td><xsl:value-of select = "lastname"/></td>
                     <td><xsl:value-of select = "nickname"/></td>
                     <td><xsl:value-of select = "marks"/></td>
                  </tr>
               </xsl:for-each>

               <xsl:for-each select = "/class/student[@rollno = 493]">
                  <tr>
                     <td><xsl:value-of select = "@rollno"/></td>
                     <td><xsl:value-of select = "firstname"/></td>
                     <td><xsl:value-of select = "lastname"/></td>
                     <td><xsl:value-of select = "nickname"/></td>
                     <td><xsl:value-of select = "marks"/></td>
                  </tr>
               </xsl:for-each>

               <xsl:for-each select = "/class/student[marks > 85]">
                  <tr>
                     <td><xsl:value-of select = "@rollno"/></td>
                     <td><xsl:value-of select = "firstname"/></td>
                     <td><xsl:value-of select = "lastname"/></td>
                     <td><xsl:value-of select = "nickname"/></td>
                     <td><xsl:value-of select = "marks"/></td>
                  </tr>
               </xsl:for-each>


            </table>

         </body>
      </html>
   </xsl:template>
</xsl:stylesheet>

Verify the output

xpath predicate