【发布时间】:2013-04-29 11:34:06
【问题描述】:
以下 XSLT 代码有效,但我想避免这五行的重复出现:
<xsl:element name="TextBlock" use-attribute-sets="Heading2">
<xsl:call-template name="process-element">
<xsl:with-param name="attr" select="'text|Text'" />
</xsl:call-template>
</xsl:element>
唯一不同的是使用的属性集。属性集取决于 LabelWrapper.theme 属性。我已经尝试过使用变量,但没有运气。
问题:
如何避免多余的代码行?
有没有更好的解决方案?
XSL 样式表:
<xsl:template match="LabelWrapper">
<xsl:choose>
<xsl:when test="./@theme = 'Heading1'">
<xsl:element name="TextBlock" use-attribute-sets="Heading1">
<xsl:call-template name="process-element">
<xsl:with-param name="attr" select="'text|Text'" />
</xsl:call-template>
</xsl:element>
</xsl:when>
<xsl:when test="./@theme = 'Emphasis'">
<xsl:element name="TextBlock" use-attribute-sets="Heading2">
<xsl:call-template name="process-element">
<xsl:with-param name="attr" select="'text|Text'" />
</xsl:call-template>
</xsl:element>
</xsl:when>
<xsl:when test="./@theme = 'Title'">
<xsl:element name="TextBlock" use-attribute-sets="Title">
<xsl:call-template name="process-element">
<xsl:with-param name="attr" select="'text|Text'" />
</xsl:call-template>
</xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:element name="TextBlock" use-attribute-sets="Normal">
<xsl:call-template name="process-element">
<xsl:with-param name="attr" select="'text|Text'" />
</xsl:call-template>
</xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
(简化的)xml 输入如下所示:
<LabelWrapper id="lblHeader" text="Big Header" theme="Heading1" />
<LabelWrapper id="lblHeader" text="normal text" theme="Normal" />
<LabelWrapper id="lblHeader" text="page title" theme="Title" />
<LabelWrapper id="lblHeader" text="Small Header " theme="Heading2" />
使用的属性集(示例)
<xsl:attribute-set name="Heading1">
<xsl:attribute name="FontFamily">Segoe UI</xsl:attribute>
<xsl:attribute name="FontSize">30px</xsl:attribute>
<xsl:attribute name="FontStyle">Normal</xsl:attribute>
<xsl:attribute name="FontWeight">Normal</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="Heading2">
<xsl:attribute name="FontFamily">Segoe UI</xsl:attribute>
<xsl:attribute name="FontSize">16px</xsl:attribute>
<xsl:attribute name="FontStyle">Normal</xsl:attribute>
<xsl:attribute name="FontWeight">Bold</xsl:attribute>
</xsl:attribute-set>
【问题讨论】:
-
我认为您应该发布一个输入 XML 示例以及您想要使用 XSLT 创建的相应输出,这样我们就更容易就如何缩短代码提出建议。根据目前提供的信息,我想知道
xsl:when test是否不应该被xsl:template match替换。但由于您的问题主要是关于缩短重复使用use-attribute-sets,我不确定是否有一种方法,因为该属性值不允许 XPath 表达式,而只是限定名称的静态列表。 -
添加了 xml 测试输入和使用的属性集示例