使用 XSLT 替换 html 锚标记中的 href 值

5 xslt

我想使用 XSLT 替换 HTML 中 href 标签的值。例如:如果锚标记是<a href="/dir/file1.htm" />,我想像这样替换 href 值:<a href="http://site/dir/file1.htm" />。关键是我想用绝对值替换所有相对网址。

我想对 HTML 内容中的所有锚标记执行此操作。如何使用 XSLT 执行此操作?

谢谢。

编辑:这是针对 Google 设备的。我在框架中显示结果,但链接在缓存页面中不起作用。它以地址栏 URL 作为根。这里的 HTML 是字符串的形式,它根据条件显示 HTML。有人可以建议一种方法来替换字符串中的所有 href 标签吗?

Dim*_*hev 2

此 XSLT 1.0 转换

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

 <xsl:param name="pServerName" select="'http://MyServer'"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="a/@href[not(starts-with(.,'http://'))]">
  <xsl:attribute name="href">
   <xsl:value-of select="concat($pServerName, .)"/>
  </xsl:attribute>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

当应用于此 XML 文档时

<html>
 <a href="/dir/file1.htm">Link 1</a>
 <a href="/dir/file2.htm">Link 2</a>
 <a href="/dir/file3.htm">Link 3</a>
</html>
Run Code Online (Sandbox Code Playgroud)

产生想要的正确结果

<html>
    <a href="http://MyServer/dir/file1.htm">Link 1</a>
    <a href="http://MyServer/dir/file2.htm">Link 2</a>
    <a href="http://MyServer/dir/file3.htm">Link 3</a>
</html>
Run Code Online (Sandbox Code Playgroud)

二. XSLT 2.0解决方案:

在 XPath 2.0 中,可以使用标准函数resolve-uri()

这种转变

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">

 <xsl:variable name="vBaseUri" select="'http://Myserver/ttt/x.xsl'"/>

 <xsl:template match="/">
  <xsl:value-of select="resolve-uri('/mysite.aspx', $vBaseUri)"/>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

当应用于任何 XML 文档(未使用)时,会产生所需的正确结果

http://Myserver/mysite.aspx
Run Code Online (Sandbox Code Playgroud)

如果样式表模块与要解析的相对 URL 来自同一服务器,则无需在参数中传递基本 uri - 执行以下操作会产生所需的结果:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">

 <xsl:variable name="vBaseUri">
  <xsl:for-each select="document('')">
   <xsl:sequence select="resolve-uri('')"/>
  </xsl:for-each>
 </xsl:variable>


 <xsl:template match="/">
  <xsl:value-of select="resolve-uri('/mysite.aspx', $vBaseUri)"/>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)