XPointer 實例
讓我們通過研究一個實例來學(xué)習(xí)一些基礎(chǔ)的 XPointer 語法。
XPointer 實例
在本例中,我們會為您展示如何使用 XPointer 并結(jié)合 XLink 來指向另外一個文檔的某個具體的部分。
我們將通過研究目標(biāo) XML 文檔開始(即我們要鏈接的那個文檔)。
目標(biāo)XML文檔
目標(biāo)XML文檔名為 "dogbreeds.xml",它列出了一些不同的狗種類:
<?xml version="1.0" encoding="ISO-8859-1"?> <dogbreeds> <dog breed="Rottweiler" id="Rottweiler"> <picture url="http://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="http://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>
注釋:上面的 XML 文檔在每個我們需要鏈接的元素上使用了 id 屬性!
XML 鏈接文檔
不止能夠鏈接到整個文檔(當(dāng)使用 XLink 時),XPointer 允許您鏈接到文檔的特定部分。如需鏈接到頁面的某個具體的部分,請在 xlink:href 屬性中的 URL 后添加一個井號 (#) 以及一個 XPointer 表達式。
表達式:#xpointer(id("Rottweiler")) 可引用目標(biāo)文檔中 id 值為 "Rottweiler" 的元素。
因此,xlink:href 屬性會類似這樣:xlink:href="http://dog.com/dogbreeds.xml#xpointer(id('Rottweiler'))"
不過,當(dāng)使用 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>