XSLT:如何根据条件更改属性

时间:2017-09-15 12:08:31

标签: xml xslt

我有这个XSLT示例:

<xsl:template match="/">
   <xsl:for-each select="elements/element">
      <xsl:if test="@type='OUTPUT-TEXT'">
        <div data-order="{order}" class="output">
            <xsl:if test="style/left_align = 'true'">
                <xsl:attribute name="class">ml-lg</xsl:attribute>
            </xsl:if>
            <xsl:if test="style/right_align = 'true'">
                <xsl:attribute name="class">mr-lg</xsl:attribute>
            </xsl:if>
            ...
            <xsl:value-of select="value" />
        </div>
      </xsl:if>
   </xsl:for-each>
</xsl:template>

我想在&#34; class&#34;中添加一些类。属性基于条件。

所以,如果我有这个xml:

<elements>
   <element type="OUTPUT-TEXT">
      <order>1</order>
      <value>Hi!</value>
      <style>
         <left_align>true</left_align>
         <right_align>false</right_align>
      </style>
   </element>
</elements>

我期待这样的事情:

<div data-order="1" class="output ml-lg">Hi!</div>

我有几个布尔,我必须评估所有并且因为它们而添加类,我必须尊重我之前的课程。

2 个答案:

答案 0 :(得分:1)

使用xsl:attribute创建属性时,它将覆盖已创建相同名称的任何现有属性。

尝试这种方式

<xsl:template match="/">
   <xsl:for-each select="elements/element">
      <xsl:if test="@type='OUTPUT-TEXT'">
        <div data-order="{order}">
            <xsl:attribute name="class">
                <xsl:text>output</xsl:text>
                <xsl:if test="style/left_align = 'true'">
                    <xsl:text> ml-lg</xsl:text>
                </xsl:if>
                <xsl:if test="style/right_align = 'true'">
                    <xsl:text> mr-lg</xsl:text>
                </xsl:if>
            </xsl:attribute>
            <xsl:value-of select="value" />
        </div>
      </xsl:if>
   </xsl:for-each>
</xsl:template>

答案 1 :(得分:1)

以下是另一种观察方式:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/elements">
   <xsl:for-each select="element[@type='OUTPUT-TEXT']">
        <div data-order="{order}">
            <xsl:attribute name="class">
                <xsl:text>output</xsl:text>
                <xsl:apply-templates select="style/*[.='true']"/>
            </xsl:attribute>
            <xsl:value-of select="value" />
        </div>
   </xsl:for-each>
</xsl:template>

<xsl:template match="left_align"> ml-lg</xsl:template>
<xsl:template match="right_align"> mr-lg</xsl:template>
<!-- add more templates here -->

</xsl:stylesheet>