Java Xml 简明教程

Java XPath Parser - Overview

XPath 是一种 XML 路径语言,用于查找 XML 文件中的信息。它是万维网联盟 (W3C) 的官方推荐。它用于遍历 XML 文档的元素和属性。XPath 提供了各种类型的表达式,可以用这些表达式从 XML 文档中查询相关信息,并且主要在 XSLT 标准中使用。

XPath is an XML Path language to find information in an XML file. It is an official recommendation of the World Wide Web Consortium (W3C). 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 and it is mainly used in XSLT standard.

XPath Terminology

  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 such as 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. Axes − XPath has thirteen different axes that retrieves the relative elements of the current element such as ancestor, child, descendant, preceding, following etc.

XPath Expressions

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

XPath uses a path expression to select node or list of nodes from an XML document. Following is a list of useful path expressions to select any node/list of nodes from an XML document.

Expressions with Predicates

XPath 表达式可以与谓词一起使用,以获取特定的节点或包含特定值的节点,并使用 […​] 定义。

XPath expressions can be used along with predicates to obtain a specific node or a node containing specific value and are defined using […​].

Expression

Result

/class/student*[1]*

Selects the first student element that is the child of the class element.

/class/student*[last()]*

Selects the last student element that is the child of the class element.

/class/student*[last()-1]*

Selects the last but one student element that is the child of the class element.

//student*[@rollno = '493']*

Selects all the student elements that have an attribute named rollno with a value of '493'