把 XML 轉成 HTML 時,如果來源文件帶有命名空間,樣式表卻沒對應宣告,比對就會全部落空——畫面上什麼都不顯示。這篇文章用 sitemap 當例子說明這個常見陷阱。
先看一份標準的 sitemap 片段(為了簡潔,省掉了部分子節點):
<urlset>
<url>
<loc>https://www.caixw.com/archives/1.html</loc>
<lastmod>2010-05-20T16:30:59+08:00</lastmod>
</url>
<url>
<loc>https://www.caixw.com/archives/2.html</loc>
<lastmod>2010-05-20T16:35:59+08:00</lastmod>
</url>
</urlset>
搭配的樣式表:
<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/xsl/Transform">
<xsl:output method="html" encoding="utf-8" indent="yes" version="1.0" />
<xsl:template match="/">
<html>
<head><title>XML Sitemap</title></head>
<body>
<xsl:apply-templates select="urlset" />
</body>
</html>
</xsl:template>
<xsl:template match="urlset">
<table>
<xsl:for-each select="url">
<tr>
<td><a>
<xsl:attribute name="href"><xsl:value-of select="loc" /></xsl:attribute>
<xsl:value-of select="loc" />
</a></td>
<td><xsl:value-of select="substring-before(lastmod, 'T')" /></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
這組組合能正確轉換,沒有問題。
但現在絕大多數 XML 文件都帶有命名空間,sitemap 也不例外:
<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<!-- ... -->
</url>
</urlset>
這時樣式表就轉不動了,body 部分一片空白。原因很直接:match="urlset" 再也比對不到節點。因為文件底下的每個節點都已經歸屬於某個命名空間,樣式表必須帶上前綴才能正確匹配。
第一步,在 xsl:stylesheet 上多宣告一個命名空間:
<xsl:stylesheet version="1.0"
xmlns:xsl="https://www.w3.org/1999/xsl/Transform"
xmlns:sitemap="https://www.sitemaps.org/schemas/sitemap/0.9">
第二步,把所有原本用來匹配 XML 節點的地方都加上 sitemap 前綴:
<xsl:template match="sitemap:urlset"> ... <td><xsl:value-of select="substring-before(sitemap:lastmod, 'T')" /></td>
做完這兩步,轉換就能恢復正常。
XSLT 1.0 的節點比對是嚴格區分命名空間的。當來源文件為元素宣告了預設命名空間,該元素在資料模型中的「名稱」其實是「命名空間 URI + 本地名稱」的組合,單純寫 urlset 只會去比對「無命名空間的 urlset」,自然永遠比不到。
實務上的建議是:拿到任何新的 XML 來源時,先確認根元素有沒有 xmlns 宣告;有的話就在樣式表中同步宣告對應前綴,並在所有 match 與 select 表達式中補上前綴,能省下大量排查時間。