# XPath

**XPath**（XML路径语言）是由[万维网联盟](https://www.edgepedia.org/zh/world-wide-web-consortium)（W3C）定义的一种表达式语言，用于寻址XML文档的各个部分，最初设计为供XSLT和XPointer共同使用。<sup>[1](https://www.w3.org/TR/xpath-10/)</sup> 其名称来自它最显著的特征——路径表达式，路径表达式以层级方式寻址XML树的节点，如同文件系统路径寻址文件那样。<sup>[2](https://www.w3.org/TR/xpath-3/)</sup> XPath也是XSLT和XQuery等其他XML标准的核心，这些标准将XPath用作它们的表达式语言。<sup>[3](https://arxiv.org/abs/2401.05112)</sup>

| 关键事实 | 详情 |
|---|---|
| 是什么 | 一种W3C表达式语言，用于寻址XML文档的各个部分，设计供XSLT和XPointer使用<sup>[1](https://www.w3.org/TR/xpath-10/)</sup> |
| 首个版本 | XPath 1.0于1999年11月16日成为W3C推荐标准，由詹姆斯·克拉克（James Clark）和史蒂夫·德罗斯（Steve DeRose）编辑<sup>[1](https://www.w3.org/TR/xpath-10/)</sup> |
| 当前版本 | XPath 3.1，2017年3月21日的W3C推荐标准，是XPath 3.0的超集<sup>[2](https://www.w3.org/TR/xpath-3/)</sup> |
| 数据模型 | XPath 3.1处理符合XQuery与XPath数据模型（XDM）3.1的值，包括XML树节点、原子值、函数项和序列<sup>[2](https://www.w3.org/TR/xpath-3/)</sup> |
| XPath 1.0类型 | 数值、字符串、布尔值和节点集<sup>[4](https://www.w3.org/TR/xpath20req/)</sup> |
| 浏览器支持 | `Document.evaluate()`方法可在HTML和XML文档上求值XPath表达式，自2015年7月起在各浏览器中可用<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate)</sup> |
| 维护状态 | XPath 1.0不计划进一步维护（包括更正已报告的错误），但它仍被广泛使用，并被其他规范规范性引用<sup>[1](https://www.w3.org/TR/xpath-10/)</sup> |

## 历史与版本

XPath的工作最初是为了给XSL转换（XSLT）与XPointer之间共享的功能提供一套通用的语法和语义，使这两种语言能用同一种记法寻址XML树中的节点。<sup>[1](https://www.w3.org/TR/xpath-10/)</sup> W3C自1998年8月18日起发布工作草案，1999年10月8日发布提议推荐标准，1999年11月16日发布最终的XPath 1.0推荐标准。<sup>[6](https://www.w3.org/standards/history/xpath-10/)</sup> 同日，W3C发布了XSLT 1.0——XPath的第一个宿主样式表语言。<sup>[7](https://www.w3.org/groups/wg/xslt/publications/)</sup>

**XPath 2.0**以序列取代了节点集，并基于XQuery 1.0与XPath 2.0数据模型（XDM）增加了模式感知和数据类型化。其第二版于2010年12月14日作为推荐标准发布。<sup>[8](https://www.w3.org/TR/xpath/)</sup> 2.0需求文档记录了其动机：显式的“存在”与“任意”量化比较、条件表达式、节点集的交集与差集（`intersect`和`except`，与1.0的并集并列），以及按XML模式定义访问元素和属性的类型化值。<sup>[4](https://www.w3.org/TR/xpath20req/)</sup> 在XPath 1.0中，诸如`5 = $ns`的比较只要5等于节点集中至少一个节点的数值即为真，无法检验所有节点；XPath 2.0增加了量化表达式，使这类语义得以显式表达。<sup>[4](https://www.w3.org/TR/xpath20req/)</sup>

**XPath 3.0**于2014年4月8日作为推荐标准发布，从原计划的XPath 2.1更名，以与“3.0”系列规范保持一致。其新特性包括字面函数项、内联函数、动态函数调用、函数项强制转换、`let`表达式，以及携带命名空间URI而非命名空间前缀的EQName。<sup>[8](https://www.w3.org/TR/xpath/)</sup>

**XPath 3.1**是2017年3月21日的推荐标准，是XPath 3.0的完全兼容超集。其最重要的新增内容是映射和数组，它们在XML之外将JSON纳入数据模型，并由配套的《函数与运算符3.1》规范中的新表达式和函数提供支持。<sup>[2](https://www.w3.org/TR/xpath-3/)</sup> 3.1规范的设计目的是供XQuery 3.1和XSLT 3.0等宿主语言规范性引用，并不打算在宿主语言之外实现。<sup>[2](https://www.w3.org/TR/xpath-3/)</sup>

## 表达式如何工作

XPath表达式针对一个上下文求值：上下文节点、上下文位置和上下文大小。<sup>[9](https://sigmodrecord.org/publications/sigmodRecord/0306/3.xpnut.pdf)</sup> 诸如`/catalog/book[@id=$book_id]`的路径选择`catalog`根元素的`book`子元素，其`id`属性满足方括号中的谓词。节点测试和谓词限制所选候选节点的集合。<sup>[10](https://citeseerx.ist.psu.edu/document?doi=8440b8c8a8af78aefd26aa6d5ef485316bb781cb&repid=rep1&type=pdf)</sup>

**轴**将导航推广到父与子之外。每一步都指定一个轴，如`child`、`descendant`、`ancestor`、`following-sibling`、`attribute`或`self`。轴分为前向轴和后向轴：前向轴包含上下文节点或在文档顺序中位于其后的节点，后向轴包含上下文节点或在文档顺序中位于其前的节点；`parent`、`ancestor`、`ancestor-or-self`、`preceding`和`preceding-sibling`是后向轴。不计属性节点和命名空间节点，一个文档被`ancestor`、`descendant`、`following`、`preceding`和`self`轴划分：这些轴彼此完全不重叠，文档中的每个节点都落在其中之一。<sup>[11](https://www.w3.org/TR/xpath20/)</sup> 每个轴都有主节点种类：属性轴为属性，命名空间轴为命名空间，其他所有轴为元素。<sup>[11](https://www.w3.org/TR/xpath20/)</sup> `namespace`轴存在于XPath 1.0中，在XPath 2.0中已弃用，应用程序改用`fn:in-scope-prefixes`等函数。<sup>[11](https://www.w3.org/TR/xpath20/)</sup>

## 浏览器与工具中的XPath

浏览器通过DOM暴露XPath。`Document`接口的`evaluate()`方法根据XPath表达式选择元素，可用于HTML和XML文档；它接受表达式、上下文节点、命名空间解析器、结果类型和结果对象。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate)</sup> 命名空间解析器将表达式中的前缀映射到命名空间URI，对于HTML文档或未使用前缀的情形，`null`很常见。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate)</sup> 结果是`XPathResult`对象，可以是单个节点或一组节点。<sup>[12](https://developer.mozilla.org/en-US/docs/Web/XML/XPath/Guides/Introduction_to_using_XPath_in_JavaScript)</sup>

在浏览器之外，许多XML处理器实现了XPath。一项2024年的差分测试研究检验了六个成熟的处理器——BaseX、eXist-DB、Saxon、PostgreSQL、libXML2和一个商业数据库系统——发现了20个独特的XPath相关逻辑错误，其中12个已修复。<sup>[3](https://arxiv.org/abs/2401.05112)</sup> 3.x系列的一致性用QT3测试套件衡量；在已发布的结果摘要中，XPath 3.1占21,597个测试用例，Saxon-EE 9.7.0.11通过了其所运行用例的99.94%。<sup>[13](https://dev.w3.org/2011/QT3-test-suite/ReportingResults31/report.html)</sup>

## XPath与CSS选择器

在Web开发中，XPath与CSS选择器在定位元素方面相互竞争。两者在常见导航上重叠：子轴对应子代组合器，后代轴对应后代组合器，属性轴对应属性选择器，而`ancestor`、`parent`或`preceding-sibling`轴大致对应CSS的`:has()`选择器。<sup>[14](https://mdn2.netlify.app/en-us/docs/web/xpath/comparison_with_css_selectors/)</sup> XPath保留了CSS所缺乏的能力，尤其是按文本内容选择节点；CSS没有标准的文本选择器，曾提议的`:contains()`从未被浏览器采纳。<sup>[15](https://geonode.com/blog/xpath-vs-css-selectors)</sup> XPath还提供`normalize-space()`等字符串函数，这往往是必需的，因为真实的HTML经过美化排版，对含空白的内容做精确文本比较会失败。<sup>[15](https://geonode.com/blog/xpath-vs-css-selectors)</sup> 对于可通过类、id、属性或后代关系实现的简单选择，CSS选择器通常更简洁，并且每个浏览器的检查器和`document.querySelectorAll`都原生支持。<sup>[15](https://geonode.com/blog/xpath-vs-css-selectors)</sup>

## 安全：XPath注入

当外部输入成为表达式语法的一部分，从而改变查询的含义时，就发生了XPath注入。与[SQL注入](https://www.edgepedia.org/zh/sql-injection)一样，能够向由用户提供的值构建的查询中注入内容的攻击者，可能绕过身份验证或读取本不应访问的数据；与SQL不同，XPath没有访问控制级别，因此注入的查询可以触及XML文档的每个部分。<sup>[16](https://cheatsheetseries.owasp.org/cheatsheets/XPath_Injection_Prevention_Cheat_Sheet.html)</sup><sup> • </sup><sup>[17](https://wstg.owasp.org/latest/4-Web_Application_Security_Testing/07-Injection/09-XPath_Injection/)</sup> 一种典型模式是提交`' or '1' = '1`作为用户名和密码，将凭据检查变成恒为真的条件。<sup>[17](https://wstg.owasp.org/latest/4-Web_Application_Security_Testing/07-Injection/09-XPath_Injection/)</sup>

推荐的防御方法是变量绑定：在应用程序代码中保持表达式固定，单独传入外部值，例如在Python的lxml中，`xml_document.xpath("/catalog/book[@id=$book_id]", book_id=requested_id)`在不改变表达式语法的前提下提供该值。仅靠编译并不能将数据与查询语法分离，临时替换引号也不能替代绑定。<sup>[16](https://cheatsheetseries.owasp.org/cheatsheets/XPath_Injection_Prevention_Cheat_Sheet.html)</sup> 当用户选择查询模式时，应用程序应将选择映射到完整的固定表达式并拒绝未知选择，而不是将选择插入路径中。<sup>[16](https://cheatsheetseries.owasp.org/cheatsheets/XPath_Injection_Prevention_Cheat_Sheet.html)</sup>

## 流式处理与大文档

标准XPath求值假定文档以树的形式驻留内存，这通常不适合流式数据。<sup>[18](https://citeseerx.ist.psu.edu/document?doi=e2ad92d7da5149bf1437e7c8ab2172529d85f00d&repid=rep1&type=pdf)</sup> 实现方通过可流式子集来解决这一问题。例如，Saxon-EE可以流式处理这样的XQuery查询：其路径表达式仅使用向下选择，其谓词是静止的，且没有任何构造会产生两个向下选择；不可流式的查询会被报告为编译时错误，而`copy-of()`和`snapshot()`函数可以为子树解除这些限制。<sup>[19](https://www.saxonica.com/html/documentation13/streaming/streamed-query.html)</sup>

## References

1. [XML Path Language (XPath) Version 1.0, W3C Recommendation 16 November 1999](https://www.w3.org/TR/xpath-10/)
2. [XML Path Language (XPath) 3.1, W3C Recommendation 21 March 2017](https://www.w3.org/TR/xpath-3/)
3. [Finding XPath Bugs in XML Document Processors via Differential Testing (XPress), ICSE 2024](https://arxiv.org/abs/2401.05112)
4. [XPath Requirements Version 2.0, W3C](https://www.w3.org/TR/xpath20req/)
5. [Document: evaluate() method, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate)
6. [XML Path Language (XPath) Version 1.0 publication history, W3C](https://www.w3.org/standards/history/xpath-10/)
7. [XSLT Working Group publications, W3C](https://www.w3.org/groups/wg/xslt/publications/)
8. [xpath cover page, W3C standards and drafts](https://www.w3.org/TR/xpath)
9. [XPath and XQuery: The XML Query Languages, SIGMOD Record](https://sigmodrecord.org/publications/sigmodRecord/0306/3.xpnut.pdf)
10. [Web and Semantic Web Query Languages, CiteSeerX](https://citeseerx.ist.psu.edu/document?doi=8440b8c8a8af78aefd26aa6d5ef485316bb781cb&repid=rep1&type=pdf)
11. [XML Path Language (XPath) 2.0 (Second Edition), W3C](https://www.w3.org/TR/xpath20/)
12. [Introduction to using XPath in JavaScript, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/XML/XPath/Guides/Introduction_to_using_XPath_in_JavaScript)
13. [QT3 Test Suite Result Summary, W3C](https://dev.w3.org/2011/QT3-test-suite/ReportingResults31/report.html)
14. [Comparison of CSS Selectors and XPath, MDN Web Docs](https://mdn2.netlify.app/en-us/docs/web/xpath/comparison_with_css_selectors/)
15. [XPath vs CSS Selectors: Capability, Readability and When to Use Each, Geonode](https://geonode.com/blog/xpath-vs-css-selectors)
16. [XPath Injection Prevention Cheat Sheet, OWASP](https://cheatsheetseries.owasp.org/cheatsheets/XPath_Injection_Prevention_Cheat_Sheet.html)
17. [XPath Injection, OWASP Web Security Testing Guide (WSTG-INJT-09)](https://wstg.owasp.org/latest/4-Web_Application_Security_Testing/07-Injection/09-XPath_Injection/)
18. [XPath Queries on Streaming Data, CiteSeerX](https://citeseerx.ist.psu.edu/document?doi=e2ad92d7da5149bf1437e7c8ab2172529d85f00d&repid=rep1&type=pdf)
19. [Saxon 13 Documentation: Streaming in XQuery, Saxonica](https://www.saxonica.com/html/documentation13/streaming/streamed-query.html)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 17, 2026; Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Databases and data systems › SQL and query languages › XML and semi-structured data query support

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/xpath

English original: https://www.edgepedia.org/xpath
