XSLT如何向copy-of添加属性

32

我在我的XSLT文件中有以下代码:

<xsl:copy-of select="/root/Algemeen/foto/node()" />

XML文件中的节点/root/Algemeen/foto/包含一个HTML图片,例如:<img src="somephoto.jpg" />

我想要做的是给这张图片添加一个固定的宽度。但是下面的代码并不起作用:

<xsl:copy-of select="/root/Algemeen/foto/node()">
    <xsl:attribute name="width">100</xsl:attribute>
</xsl:copy-of>
1个回答

54

xsl:copy-of会深度复制所选节点,但不提供改变它的机会。

你需要使用xsl:copy,然后在内部添加其他节点。 xsl:copy只复制节点和命名空间属性,而不是常规属性和子节点,因此您需要确保使用apply-templates将其他节点也传递出去。 xsl:copy没有@select,它适用于当前节点,因此您需要将<xsl:copy-of select="/root/Algemeen/foto/node()" />的应用位置改为<xsl:apply-templates select="/root/Algemeen/foto/node()" />并将img逻辑移到模板中。

类似这样:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <result>
    <xsl:apply-templates select="/root/Algemeen/foto/img"/>
        </result>
    </xsl:template>

<!--specific template match for this img -->
    <xsl:template match="/root/Algemeen/foto/img">
      <xsl:copy>
            <xsl:attribute name="width">100</xsl:attribute>
            <xsl:apply-templates select="@*|node()" />
          </xsl:copy>
    </xsl:template>

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

</xsl:stylesheet>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接