如果给定元素具有给定的 "magic value",则插入新的 XML 元素?

Insert new XML element if a given element has a given "magic value"?

我们正在处理一个遗留系统,其 XML 输出未根据模式定义且不是最优的,因此我们实际上定义了我们自己的更好的模式并将 XSL 转换应用于接收到的 XML 使其匹配。

收到的 XML 中的一个特殊情况是“哦,如果这个字段有一个特殊的 'magic value' 它意味着与正常不同的东西。所以我们想添加一个规则。例如给定:

<SomeObject>
  <Id>123</123>
  <UpdateCount>-1</UpdateCount>
</SomeObject>

输出:

<SomeObject>
  <Id>123</123>
  <UpdateCount xsi:nil='true'/> //we don't HAVE to have this but it's preferred
  <Deleted>true</Deleted>
</SomeObject>

理想情况下,对于 UpdateCount 的所有其他值,我们将添加 <Deleted>false</Deleted> 但这同样不是必需的,我们可以将此 属性 设为可选,它只会让事情变得更简单凌乱

你可以这样做:

<xsl:template match="UpdateCount[. = -1]">
    <UpdateCount xsi:nil="true"/>
    <Deleted>true</Deleted>
</xsl:template>

或者:

<xsl:template match="UpdateCount">
    <xsl:choose>
        <xsl:when test=". = -1">
            <UpdateCount xsi:nil="true"/>
            <Deleted>true</Deleted>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy-of select="."/>
            <Deleted>false</Deleted>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>