开发者

XSLT 1.0: analyze the variation of a setting

开发者 https://www.devze.com 2023-04-11 12:18 出处:网络
I have block of data sample in XML. Each data has a attribute called \"switch\" specifying if a switch is off or on ( default value is off ).

I have block of data sample in XML. Each data has a attribute called "switch" specifying if a switch is off or on ( default value is off ). The goal is to add this information thanks to XSLT as an attribute of the block. This new atttribute "action" specifies whether the switch was turned off or on within the data block.

Case 1:

<block>
    <data switch="true">2.4</data>  
    <data switch="true">2.4</data开发者_如何学C>
    <data>270.0</data>
    <data>244.79999999999998</data>
    <data>330.59999999999997</data>
</block>

transformed in

<block action="turnedOFF">
    <data switch="true">2.4</data>
    <data switch="true">2.4</data>
    <data>270.0</data>
    <data>244.79999999999998</data>
    <data>330.59999999999997</data>
</block>

Case 2: Reversely, the xml below:

<block>
    <data>270.0</data>
    <data>244.79999999999998</data>
    <data>330.59999999999997</data>
    <data switch="true">2.4</data>
    <data switch="true">2.4</data>
</block>

is to be transformed into:

<block action="turnedON">
    <data>270.0</data>
    <data>244.79999999999998</data>
    <data>330.59999999999997</data>
    <data switch="true">2.4</data>
    <data switch="true">2.4</data>
</block>


If you know there can be at most one transition of the switch attribute in the <data> elements, it should be enough to check the values of the first and last <data> element in a <block>. Here's an untested attempt:

<?xml version="1.0" encoding="utf-8"?>

<xsl:template match="block">
    <block>
        <xsl:if test="data[1]/@switch and not(data[last()]/@switch)">
            <xsl:attribute name="action">turnedOFF</xsl:attribute>
        </xsl:if>
        <xsl:if test="not(data[1]/@switch) and data[last()]/@switch">
            <xsl:attribute name="action">turnedON</xsl:attribute>
        </xsl:if>
        <xsl:apply-templates select="@*|node()" />
    </block>
</xsl:template>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

Update I fixed a few errors and verified the transform. This works.

0

精彩评论

暂无评论...
验证码 换一张
取 消