使用 XSLT 根据条件操作 XML 键/值 [英] XML Key/value manipulation on condition using XSLT

查看:22
本文介绍了使用 XSLT 根据条件操作 XML 键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据 -

<item>
    <name>Bob</name>
    <fav_food>pizza</fav_food>
    <key>Salary</key>
    <value />
    <value2>1000</value2>
    <value3 />
</item>

我希望我的输出看起来像这样 -

I want my output to look like this -

<item>
    <name>Bob</name>
    <fav_food>pizza</fav_food>
    <Salary>1000</Salary>
</item>

在这种情况下,Salary 的值为 1000,因为 value 为空而 value2 不是(value 的优先级高于 value2,而 value2 的优先级高于 value3).

In this case, Salary gets the value of 1000 because value is empty and value2 is not (value has higher priority than value2, which has higher priority than value3).

保证value、value2和value3都存在,并且只有一个是非空的.是否可以使用 XSLT 转换来执行此操作?

It is guaranteed that value,value2 and value3 all exist, and only one of those is nonempty. Is it possible to use a XSLT transform to do this?

目前,这是我的变换.

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*" />  

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

<xsl:template match="key">
    <xsl:element name="{substring-before(substring-after(.,'{'),'}')}"> 
        <xsl:choose>
            <xsl:when test="value != ''">
                <xsl:value-of select="following-sibling::value" />
            </xsl:when>
            <xsl:when test="value2 != ''">
                <xsl:value-of select="following-sibling::value2" />
            </xsl:when>
            <xsl:when test="value3 != ''">
                <xsl:value-of select="following-sibling::value3" />
            </xsl:when>
        </xsl:choose>
   </xsl:element> 
</xsl:template>
</xsl:stylesheet>

推荐答案

我认为你可以简单地做

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*" />  

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

<xsl:template match="key">
  <xsl:element name="{.}">
    <xsl:copy-of select="../(value, value2, value3)/text()"/>
  </xsl:element>
</xsl:template>

<xsl:template match="item/value | item/value2 | item/value3"/>

</xsl:stylesheet>

您可能想要或需要调整元素名称生成,但我没有应用您的 name="{substring-before(substring-after(.,'{'),'}')}",因为我在您的输入示例中没有看到任何大括号.

You might want or need to adjust the element name generation but I have not applied your name="{substring-before(substring-after(.,'{'),'}')}" as I don't see any braces in your input sample.

这篇关于使用 XSLT 根据条件操作 XML 键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆