【问题标题】:How to conditionally transform multiple XML elements into one element using XSLT?如何使用 XSLT 有条件地将多个 XML 元素转换为一个元素?
【发布时间】:2014-08-25 14:18:09
【问题描述】:

假设我有两种类型的 XML 元素,其文本内容可以是“真”或“假”:

<elementA>true</elementA>, 
<elementB>false</elementB> 

我想创建一个新元素

<result>$content</result> 

其中变量 $content 基于两个输入元素值可以有 4 种类型的值:

真的,真的 -> 一个

真,假-> B

假,真 -> C

假,假-> D

我试图用 xsl:function 解决这个问题,但不知道如何同时选择这两个元素(我对 xslt 几乎没有经验)。 是否可以进行这种转换?

编辑

我正在尝试您的第二种解决方案,但是我的主要问题来源是我不知道如何将变量传递给我的函数。目前我有以下代码:

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

<xsl:function name="transform">
    <xsl:param name="p1"></xsl:param>
    <xsl:param name="p2"></xsl:param>
    <xsl:choose>
        <xsl:when test="$p1='true' and $p2='true'">
            <orderingType>RND</orderingType>
        </xsl:when>
        <xsl:when test="$p1='true' and $p2='false'">
            <orderingType>FIX</orderingType>
        </xsl:when>
        <xsl:when test="$p1='false' and $p2='false'">
            <orderingType>PREF</orderingType>
        </xsl:when>
    </xsl:choose>
</xsl:function>

<xsl:template match="//action/*">
    <xsl:variable name="var1" select="shuffle"></xsl:variable>
    <xsl:variable name="var2" select="limitOn"></xsl:variable>

</xsl:template>

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    怎么样:

    <xsl:variable name="index" select="2*(elementA='false') + (elementB='false')" />
    <result>
        <xsl:value-of select="substring('ABCD', $index + 1, 1)" />
    </result>
    

    或者,使用xsl:choose 并在xsl:when 指令中明确指定每种情况及其结果:

    <xsl:choose>
        <xsl:when test="elementA='true' and elementB='true'">A</xsl:when>
        <xsl:when test="elementA='true' and elementB='false'">B</xsl:when>
        <xsl:when test="elementA='false' and elementB='true'">C</xsl:when>
        <xsl:otherwise>D</xsl:otherwise>
    </xsl:choose>
    

    【讨论】:

    • 编辑了我的问题以澄清我的误解来源。我的问题主要是我不知道如何传递变量。
    • @Greg 你真的需要这个函数吗? IOW,您是否需要在样式表的不同位置多次执行相同的操作?
    【解决方案2】:

    模板应该这样做;

    <xsl:template match="xml-fragment">
        <xsl:variable name="p1">
            <xsl:value-of select="elementA"/>
        </xsl:variable>
        <xsl:variable name="p2">
            <xsl:value-of select="elementB"/>
        </xsl:variable>     
        <xsl:choose>
            <xsl:when test="$p1='true' and $p2='true'">
                <orderingType>RND</orderingType>
            </xsl:when>
            <xsl:when test="$p1='true' and $p2='false'">
                <orderingType>FIX</orderingType>
            </xsl:when>
            <xsl:when test="$p1='false' and $p2='false'">
                <orderingType>PREF</orderingType>
            </xsl:when>
        </xsl:choose>       
    </xsl:template>
    

    【讨论】:

    • 谢谢大家,终于用类似的模板解决了。
    猜你喜欢
    • 2012-01-25
    • 2010-10-13
    • 2018-09-22
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多