css - 重复添加/append 类到输出元素

标签 css class xslt append

我基本上有一个像这样的 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/

相关文章:

c++ - 类模板方法特化

java - LibGDX 访问另一个类中的动画?

android - forName 找不到类

css - 如何使用户选择适用于 Safari 浏览器

html - 如何设置页眉和页脚之间的 div 样式以始终占据 100% 的剩余空间?

css - 如何使用文本正下方的伪元素画一条线并忽略填充?

xml - 在 XSL 中的一个选择中调用两次 translate()

Javascript 显示/隐藏 div 并根据可见的 div 更改 css 类?

java - 将 xml 转换为另一个 xml 的最简单方法是什么?

xml - 如何使用 XSLT-1.0 转换 xml 结构