我基本上有一个像这样的 XML 输入结构:
...
<box type="rectangle" class="someOriginalClass">
<background bgtype="solid" />
<animation order="3" />
... children
</box>
并想将其转换为
<div class="someOriginalClass rectangle solid animated order3">
...children
</div>
请注意,背景和动画都不需要存在,这是一个简化的示例,这意味着可以有更多类似的属性,具有更多属性。 同样,动画和背景在其他地方重复使用。
到目前为止,我的 XSLT 代码是:
<xsl:template match="box">
<div class="{@someOldClass} {@type}">
<xsl:apply-templates select="./*" />
</div>
</xsl:template>
<xsl:template match="background">
<xsl:attribute name="class">
<xsl:value-of select="@bgtype"/>
</xsl:attribute>
</xsl:template>
<xsl:template match="animation">
<xsl:attribute name="class">
animated order<xsl:value-of select="@order"/>
</xsl:attribute>
</xsl:template>
这段代码的问题是每个模板都完全覆盖了类属性,忽略了已经包含的类。
为了解决这个问题,我试过:
a) 重写旧类 => value-of 只获取输入 XML 类 (someOldClass)
<xsl:template match="animation">
<xsl:attribute name="class">
<xsl:value-of select="../@class"/>
animated order<xsl:value-of select="@order"/>
</xsl:attribute>
</xsl:template>
b) 而不是使用参数在模板之间传递更改 => 仅一次,一种方式
<xsl:template match="box">
<div class="{@someOldClass} {@type}">
<xsl:apply-templates select="./*">
<xsl:with-param name="class" select="concat(@someOldClass,' ',@type)"/>
</xml:apply-templates>
</div>
</xsl:template>
<xsl:template match="animation">
<xsl:param name="class"/>
<xsl:attribute name="class">
<xsl:value-of select="$class"/>
animated order<xsl:value-of select="@order"/>
</xsl:attribute>
</xsl:template>
你看,我缺少一个解决方案,它可以处理任意数量的类更新,并且冗余最少。 顺便说一句,我是一名 XSLT 初学者,所以也许有一些我还没有遇到的注定的功能。
有什么想法吗?
最佳答案
我以前用过这个。我不确定您的 XML 是什么样子,但这可能有助于您走上正确的道路。
<xsl:template match="box">
<xsl:param name="boxType" />
<li>
<xsl:variable name="boxClass">
<xsl:value-of select="$boxType"/>
<xsl:if test="@class1 = 1"> class1</xsl:if>
<xsl:if test="@class2 = 1"> class2</xsl:if>
<xsl:if test="@class3 = 1"> class3</xsl:if>
<xsl:if test="@class4 = 1"> class4</xsl:if>
<xsl:if test="@last = 1"> lnLast</xsl:if>
</xsl:variable>
<xsl:attribute name="class">
<xsl:value-of select="$boxClass"/>
</xsl:attribute>
</li>
</xsl:template>
关于css - 重复添加/append 类到输出元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12677756/