Xpath 简明教程
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.
-
Root
-
Element
-
Text
-
Attribute
-
Comment
-
Processing Instruction
-
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>