如何在<xsl:attribute>标签内去除空格?

6
在XSLT样式表中,我如何在<xsl:attribute>标记内移除前导和尾随空格?
例如,以下样式表:
<xsl:template match="/">
  <xsl:element name="myelement">
    <xsl:attribute name="myattribute">
      attribute value
    </xsl:attribute>
  </xsl:element>
</xsl:template>

输出:

<myelement myattribute="&#10;      attribute value&#10;    "/>

虽然我希望它输出:
<myelement myattribute="attribute value"/>

除了将<xsl:attribute>的开始和结束标记合并成一行以外,还有其他实现方法吗?

因为如果属性值不是纯文本行,而是某些复杂计算的结果(例如使用或标签),则将所有代码合并成一行以避免前导和尾随空格将导致样式表非常丑陋。

1个回答

7
您可以使用xsl:text或xsl:value-of将文本包装起来:
<xsl:template match="/">
    <xsl:element name="myelement">
        <xsl:attribute name="myattribute">
            <xsl:text>attribute value</xsl:text>
        </xsl:attribute>
    </xsl:element>
</xsl:template>

或者

<xsl:template match="/">
    <xsl:element name="myelement">
        <xsl:attribute name="myattribute">
            <xsl:value-of select="'attribute value'"/>
        </xsl:attribute>
    </xsl:element>
</xsl:template>

这对你有帮助吗?如果不是,请用一句话解释一下你的问题。

请注意Michael Kay的评论,它把问题说明得很到位!


问题在于,如果属性值是某些复杂计算的结果,例如使用<xsl:choose>元素,则将所有代码折叠成一行以获得所需结果会使样式表看起来非常丑陋。 - Theodore Lytras
2
你可以在xsl:attribute和xsl:choose之间使用换行符。 但要避免在文本节点中使用换行符。 所有文本节点中的换行符都会出现在输出结果中。 所有xsl元素之间的换行符都将被忽略。 - Matthias M
1
好的,我明白了。在我的实际情况中,<xsl:choose> 被文本节点“夹住”了;将每个节点都用 <xsl:text> 包装起来可以有效地去除空格。问题解决了,谢谢! - Theodore Lytras
1
请记住,空格文本节点无论如何都会被折叠。唯一的问题是与非空格相邻的空格。为了消除这个问题,您需要在xsl:text中包装重要文本。 - Michael Kay

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