Xpath 简明教程

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.