我们需要在src属性参数中找到并替换路径
<?xml version="1.0"?>
<ul>
<img src="/assets/myimage.png"/>
</ul>
以下是我的1.0中的XSLT
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:template name="globalReplace">
<xsl:param name="outputString"/>
<xsl:param name="target"/>
<xsl:param name="replacement"/>
<xsl:choose>
<xsl:when test="contains($outputString,$target)">
<xsl:value-of select="concat(substring-before($outputString,$target),$replacement)" />
<xsl:call-template name="globalReplace">
<xsl:with-param name="outputString" select="substring-after($outputString,$target)" />
<xsl:with-param name="target" select="$target" />
<xsl:with-param name="replacement" select="$replacement" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$outputString"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="@src">
<xsl:call-template name="globalReplace">
<xsl:with-param name="outputString" select="."/>
<xsl:with-param name="target" select="'/assets/'"/>
<xsl:with-param name="replacement" select="'/images/'"/>
</xsl:call-template>
</xsl:template>
<xsl:template match="/ | node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*">
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
第1期 我们在执行转换时得到以下结果
<img>/images/myimage.png</img>
而不是
<img src="/images/myimage.png"/>
第2期
XSLT转换不保留
之类的属性<img src="/images/myimage.png" height="20"/>
我有一个为XSLT2.0提供的解决方案,但找不到任何引用。提前谢谢!
答案 0 :(得分:1)
您可以添加定义例外的副本模板到@src
模板:
<xsl:template match="img/@*">
<xsl:copy>
<xsl:apply-templates select="@*" />
</xsl:copy>
</xsl:template>
这会保留img
标记及其属性的原始状态。
答案 1 :(得分:1)
您可以在 globalReplace 模板中更轻松地进行替换,并将匹配项设置为<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:template name="globalReplace">
<xsl:param name="param.str"/>
<xsl:param name="param.target"/>
<xsl:param name="param.replacement"/>
<xsl:choose>
<xsl:when test="contains($param.str, $param.target)">
<xsl:value-of select="concat(substring-before($param.str, $param.target), $param.replacement, substring-after($param.str, $param.target))"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$param.str"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@src[parent::img]">
<xsl:attribute name="src">
<xsl:call-template name="globalReplace">
<xsl:with-param name="param.str" select="."/>
<xsl:with-param name="param.target" select="'/assets/'"/>
<xsl:with-param name="param.replacement" select="'/images/'"/>
</xsl:call-template>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
,请参阅下面的XSL:
<ul>
<img src="/images/myimage.png"/>
</ul>
然后你的结果将是:
int i