Skip to content

XML XPointer

XPointer 扩展了 XPath,允许超链接(通常使用 XLink 定义)指向 XML 文档内的特定片段(fragment)或部分,而不仅仅是整个文档。

  • XPointer 可以在 XML 资源中定位特定的点、范围或元素。
  • 它利用 XPath 表达式在目标 XML 文档中进行导航。
  • 它允许比标准 URL 片段标识符(如 #id)更细粒度的链接。
  • XPointer 是 W3C 推荐标准,但实际应用有限。

主要 Web 浏览器几乎没有对 XPointer(和 XLink)的原生支持。你不能依赖标准浏览器自动解析基于 XPointer 的链接。

然而,在专门的 XML 处理工具、文档管理系统或需要细粒度内部链接的特定 XML 标准中,可能会遇到其概念和语法。

我们来演示如何将 XPointer 与 XLink 结合使用,创建指向另一个 XML 文档特定部分的链接。

目标 XML 文档 (dogbreeds.xml):

注意此处使用了 xml:id,它是用于分配唯一 ID 的标准 XML 属性。

<?xml version="1.0" encoding="UTF-8"?>
<dogbreeds xmlns:xml="http://www.w3.org/XML/1998/namespace">
<dog breed="Rottweiler" xml:id="Rottweiler">
<picture url="http://example.com/rottweiler.jpg"/>
<history>The Rottweiler's ancestors were probably Roman drover dogs...</history>
<temperament>Confident, bold, alert and imposing...</temperament>
</dog>
<dog breed="FCRetriever" xml:id="FCRetriever">
<picture url="http://example.com/fcretriever.jpg"/>
<history>One of the earliest uses of retrieving dogs was to help fishermen...</history>
<temperament>The flat-coated retriever is a sweet, exuberant, lively dog...</temperament>
</dog>
</dogbreeds>

源 XML 文档 (mydogs.xml):

此文档使用 XLink(xlink:href、xlink:type)链接到 dogbreeds.xml 的部分内容。

<?xml version="1.0" encoding="UTF-8"?>
<mydogs xmlns:xlink="http://www.w3.org/1999/xlink">
<mydog>
<description>Anton is my favorite dog. He has won many awards...</description>
<!-- Link using XPointer full syntax -->
<fact xlink:type="simple"
xlink:href="dogbreeds.xml#xpointer(id('Rottweiler'))">
Fact about Rottweiler (Full XPointer)
</fact>
</mydog>
<mydog>
<description>Pluto is the sweetest dog on earth...</description>
<!-- Link using XPointer shorthand for IDs -->
<fact xlink:type="simple"
xlink:href="dogbreeds.xml#FCRetriever">
Fact about Flat-Coated Retriever (Shorthand)
</fact>
</mydog>
</mydogs>

解释:

  • xlink:href 属性包含目标文档的 URL(dogbreeds.xml),后跟一个井号(#)和 XPointer 表达式。
  • xpointer(id('Rottweiler')): 这是完整的 XPointer 语法。它使用类似 XPath 的函数 id() 来查找 xml:id 属性值为 ‘Rottweiler’ 的元素。
  • #FCRetriever: 这是 XPointer 的简写(shorthand)语法。如果井号后的部分与目标文档中某个 xml:id 属性的值匹配,它会直接指向该元素。

虽然概念上很强大,但由于缺乏广泛实现,XPointer 主要只在特定、封闭的 XML 生态系统或为了理解 XML 技术的历史和能力时才相关。