如何在XSLT样式表中声明命名空间

考虑以下两段代码:

 

1 <urlset>
2 <url>
3 <loc>http://www.caixw.com/archives/1.html</loc>
4 <lastmod>2010-05-20T16:30:59+08:00</lastmod>
5 </url>
6 <url>
7 <loc>http://www.caixw.com/archives/2.html</loc>
8 <lastmod>2010-05-20T16:35:59+08:00</lastmod>
9 </url>
10  </urlset>

 

这是一段标准的sitemap文件,当然为简单点,我把url的两个子节点去掉了,但总体上不影响我们使用。

 

1 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/Transform">
2  <xsl:output method="html" encoding="utf-8" indent="yes" version="1.0" />
3  <xsl:template match="/" xmlns:sm="http://www.sitemaps.org/schemas/sitemap/0.9">
4  <html>
5 <head>
6 <title>XML Sitemap</title>
7 </head>
8 <body>
9 <xsl:apply-templates select="urlset" />
10 </body>
11  </html>
12  </xsl:template>
13  <xsl:template match="urlset">
14  <table>
15 <xsl:for-each select="url">
16 <tr>
17 <td><a>
18 <xsl:attribute name="href"><xsl:value-of select="loc" /></xsl:attribute>
19 <xsl:value-of select="loc" />
20 </a></td>
21 <td><xsl:value-of select="substring-before(lastmod, 'T')" /></td>
22 </tr>
23 </xsl:for-each>
24  </table>
25  </xsl:template>
26  </xsl:stylesheet>

 

 

 

 

 

 

这是一段转换sitemap的代码,再次偷懒,把输出的表格的内容给过滤掉了一部分。要完整版的看本站右下角的sitemap文件。

以上这两段代码能够正确的进行转换,没有什么问题。现在我们给xml文件加上一个命名空间(事实上现在大部分XML文件都存在这样那样的命名空间,sitemap也不例外):

 

1 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
2 <url>
3 <!-- ... -->
4 </url>
5  </urlset>

 

OK,现在应该不能正确转换了,body部分变成空的了。很明显无法匹配urlset节点了。因为现在所有sitemap文件下的节点都是带命名空间的,不能再这样直接使用了。都要带上命名空间前缀才能正确匹配。

当然,要使用命名空间,首先要声明它。在xsl:stylesheet标签中再声明一个命名空间:

 

1 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/Transform" xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9">

 


本文采用 知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议 进行许可。 
首发于本人博客:http://www.caixw.com/archives/how-to-declare-namespace-in-xslt-stylesheet.html

 

 

 

 

 

 

 

 

 

posted @ 2010-07-16 12:26  caixw  阅读(345)  评论(0)    收藏  举报