XML密钥/使用XSLT条件值操作(XML Key/value manipulation on co

2019-10-18 07:02发布

我有这样的数据 -

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

我想我的输出看起来像这样 -

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

在这种情况下,工资得到的1000值,因为值是空的和value2不是(值比值2,其比值3具有较高的优先级更高的优先级)。

这是保证值,值2和值3都存在,只是其中的一个是空的。 是否有可能使用XSLT转换来做到这一点?

目前,这是我的变换。

<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>

Answer 1:

我想你可以简单地做

<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(.,'{'),'}')}" ,因为我没有看到任何大括号在您输入采样。



文章来源: XML Key/value manipulation on condition using XSLT