如何在rss中使用带有名称空间的自定义标记



我正在尝试为rss提要创建带有命名空间的自定义标记。我已经列出了我的两个文件rss.xml&下面的rss.xsl供参考。如果我从xml文档中删除rss元素,它就可以正常工作。对于rss元素,它不起作用。

有人知道吗?

这是我的XML文档-rss.XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="rss.xsl"?>
<rss version='2.0' xmlns:SL="http://mywebsite.com/course.xsd">
<channel><description>mywebsite Course RSS Feed</description><link>http://www.mywebsite.com</link><title>mywebsite Courses</title>
<SL:Courses>
<SL:Course>
<SL:ID>18</SL:ID>
<SL:Name>ITIL<sup>®</sup> Foundation</SL:Name>
<SL:WorkshopId>17369</SL:WorkshopId>
<SL:PackageId>46</SL:PackageId>
<SL:Dates>11-Jan-2014,12-Jan-2014</SL:Dates>
<SL:StartDate>11-Jan-2014</SL:StartDate>
<SL:EndDate>12-Jan-2014</SL:EndDate>
<SL:StartTiming>09:30</SL:StartTiming>
<SL:EndTiming>18:30</SL:EndTiming>
<SL:CityId>55</SL:CityId>
<SL:CityName>PUNE</SL:CityName>
<SL:CountryId>6</SL:CountryId>
<SL:CountryName>INDIA</SL:CountryName>
</SL:Course>
</SL:Courses>
</channel>
</rss>

这是我的xsl文档-rss.xsl

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="html" indent="yes" doctype-system='http://www.w3.org/TR/html4/strict.dtd' doctype-public='-//W3C//DTD HTML 4.01//EN' />
<xsl:template match="/">
<html>
<head>
<title>test</title>
</head>
<body>
<xsl:apply-templates select="//*[local-name()='Courses']" />
</body>
</html>
</xsl:template>
<xsl:template match="//*[local-name()='Courses']">
<table cellpadding="2" cellspacing="0" border="0" width="75%">
<xsl:apply-templates select="//*[local-name()='Course']" />
</table>
</xsl:template>
<xsl:template match="//*[local-name()='Course']">
<!-- ... -->
<tr>
<td colspan="2" style="text-align:left;padding-top:10px;">
<xsl:value-of select="//*[local-name()='Name']" disable-output-escaping="yes" /><br />
</td>
<td colspan="2" style="text-align:left;padding-top:10px;">
<xsl:value-of select="//*[local-name()='Dates']" disable-output-escaping="yes" /><br />
</td>
</tr>
<!-- ... -->
</xsl:template>
</xsl:stylesheet>

EDIT(感谢@nwellnhof):rss元素没有以SL:为前缀。因此,即使它为其子元素分配了名称空间,它也会保留在默认名称空间中。

换句话说,如果希望模板与rss匹配,则可以在不添加名称空间前缀的情况下执行此操作。另一方面,为了匹配rss的子代,您需要声明它们的命名空间(或使用local-name())。

因此,输入XML中存在的名称空间也必须在XSLT样式表中声明:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:SL="http://mywebsite.com/course.xsd">

请注意,使用local-name()并不能避免名称空间,而是一种可靠的标识元素的方法。如果如上所示添加前缀为SL的命名空间,只需为模板匹配的SL加前缀,而不是匹配其本地名称:

<xsl:template match="SL:Courses">

现在,如何重写样式表?从匹配文档节点开始,就像你已经做过的那样:

<xsl:template match="/">

然后,插入一个匹配rss(n.b.,没有名称空间前缀)的模板,例如:

<xsl:template match="rss">
<xsl:apply-templates/>
</xsl:template>

以下模板必须包含SL前缀,例如:

<xsl:template match="SL:Name">

最新更新