第一次同時把命名空間、Schema 與 XSLT 串在一起,比想像中折騰。這裡把最終能正常運作的結果完整記錄下來,順便談談踩到的坑,希望讓你少走一點冤枉路。
需求很單純:用一份 XML 描述網站選單,加上命名空間與 Schema 驗證,再用 XSLT 轉成 HTML。
<?XML version="1.0" encoding="GB2312"?>
<menu_items>
<menu_item href="index.Html" image="images/A1.gif" name="首頁"/>
<menu_item href="ep.Html" image="images/A2.gif" name="新聞">
<menu_item href="ep.Html" image="images/A2.gif" name="國內新聞"/>
</menu_item>
</menu_items>
結構很直觀:menu_item 可以自我關閉,也可以向下嵌套一層子選單。
用 XMLSpy 的 Generate Schema 功能自動生成,再手動修飾幾個屬性後得到:
<?XML version="1.0" encoding="GB2312"?>
<xs:schema xmlns="https://www.hz-sp.com/2005/XMLSchema-menu"
xmlns:xs="https://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.hz-sp.com/2005/XMLSchema-menu">
<xs:element name="menu_item">
<xs:complexType>
<xs:sequence>
<xs:element ref="menu_item" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="href" type="xs:anyURI" use="optional"/>
<xs:attribute name="image" type="xs:anyURI" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="menu_items">
<xs:complexType>
<xs:sequence>
<xs:element ref="menu_item" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
幾個刻意的選擇:menu_item 用遞迴的 ref 指向自己,子選單的 minOccurs 設為 0,所以它可以沒有子項;name 標成 use="required",而 href 與 image 用 xs:anyURI 型別並標為 optional。其中 https://www.hz-sp.com/2005/XMLSchema-menu 就是我的命名空間。
用 XMLSpy 的 Assign Schema 指定這份 xsd 之後,XML 的根節點變成:
<menu_items xmlns="https://www.hz-sp.com/2005/XMLSchema-menu"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.hz-sp.com/2005/XMLSchema-menu
menu.xsd">
schemaLocation 是「命名空間 → 檔案位置」的配對清單,驗證器靠它找到對應的 xsd。
<?XML version="1.0" encoding="GB2312"?>
<xsl:stylesheet xpath-default-namespace="https://www.hz-sp.com/2005/XMLSchema-menu"
version="2.0"
xmlns:xsl="https://www.w3.org/1999/XSL/Transform"
xmlns:xs="https://www.w3.org/2001/XMLSchema"
xmlns:fn="https://www.w3.org/2004/07/xpath-functions"
xmlns:xdt="https://www.w3.org/2004/07/xpath-datatypes"
xmlns="https://www.w3.org/1999/xhtml">
<xsl:output encoding="GB2312" indent="yes" method="html" version="4.0"/>
<xsl:template match="mm:menu_items" xmlns:mm="https://www.hz-sp.com/2005/XMLSchema-menu">
<table width="900" border="0" cellspacing="0" cellpadding="0">
<tr>
<xsl:for-each select="mm:menu_item">
<a href="{@href}">
<img src="{@image}" width="113" height="57" border="0"/>
</a>
</xsl:for-each>
</tr>
</table>
</xsl:template>
</xsl:stylesheet>
最惱人的一點是:xpath-default-namespace 對 xsl:template 的 match 沒有作用。這其實說得通——match 用的是模式(pattern)語法,並非完整的 XPath 表達式,所以它不吃這個屬性,必須像範例那樣在 match 上自行宣告前綴。
奇怪的是,這個屬性對 for-each 的 select 也沒生效,那就比較令人費解了,只能推測是處理器對該屬性的支援範圍與我理解的不一致。實務上的結論很樸素:前綴自己寫清楚,別依賴預設命名空間的預期行為,會省下大量除錯時間。