Latest web development tutorials

XPointer 實例

讓我們通過研究一個實例來學習一些基礎的XPointer 語法。


XPointer 實例

在本例中,我們會為您展示如何使用XPointer 並結合XLink 來指向另外一個文檔的某個具體的部分。

我們將通過研究目標XML 文檔開始(即我們要鏈接的那個文檔)。


目標XML文檔

目標XML文檔名為"dogbreeds.xml",它列出了一些不同的狗種類:

<?xml version="1.0" encoding="ISO-8859-1"?>

<dogbreeds>

<dog breed="Rottweiler" id="Rottweiler">
<picture url="../../dog.com/rottweiler.gif" />
<history>The Rottweiler's ancestors were probably Roman
drover dogs.....</history>
<temperament>Confident, bold, alert and imposing, the Rottweiler
is a popular choice for its ability to protect....</temperament>
</dog>

<dog breed="FCRetriever" id="FCRetriever">
<picture url="../../dog.com/fcretriever.gif" />
<history>One of the earliest uses of retrieving dogs was to
help fishermen retrieve fish from the water....</history>
<temperament>The flat-coated retriever is a sweet, exuberant,
lively dog that loves to play and retrieve....</temperament>
</dog>

</dogbreeds>

在您的瀏覽器查看"dogbreeds.xml"文件

注意上面的XML文檔在每個我們需要鏈接的元素上使用了id屬性!


XML 鏈接文檔

不止能夠鏈接到整個文檔(當使用XLink 時),XPointer 允許您鏈接到文檔的特定部分。 如需鏈接到頁面的某個具體的部分,請在xlink:href 屬性中的URL 後添加一個井號(#) 以及一個XPointer 表達式。

表達式: #xpointer(id("Rottweiler"))可引用目標文檔中id值為"Rottweiler"的元素。

因此,xlink:href屬性會類似這樣: xlink:href="http://dog.com/dogbreeds.xml#xpointer(id('Rottweiler'))"

不過,當使用id 鏈接到某個元素時,XPointer 允許簡寫形式。 您可以直接使用id的值,就像這樣: xlink:href="http://dog.com/dogbreeds.xml#Rottweiler"

下面的XML 文檔可引用每條狗的品種信息,均通過XLink 和XPointer 來引用:

<?xml version="1.0" encoding="ISO-8859-1"?>

<mydogs xmlns:xlink="http://www.w3.org/1999/xlink">

<mydog xlink:type="simple"
xlink:href="http://dog.com/dogbreeds.xml#Rottweiler">
<description xlink:type="simple"
xlink:href="http://myweb.com/mydogs/anton.gif">
Anton is my favorite dog. He has won a lot of.....
</description>
</mydog>

<mydog xlink:type="simple"
xlink:href="http://dog.com/dogbreeds.xml#FCRetriever">
<description xlink:type="simple"
xlink:href="http://myweb.com/mydogs/pluto.gif">
Pluto is the sweetest dog on earth......
</description>
</mydog>

</mydogs>