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

37 Views Asked by At

We're dealing with a legacy system whose XML output is not defined against a schema and not optimal, so we're actually defining our own, nicer schema and applying XSL transforms to the received XML to make it match.

One special case in the received XML is "oh, if this field has a special 'magic value' it means something different to normal. So we want to add a rule. e.g. given:

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

Output:

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

Ideally, for all other values of UpdateCount we would add <Deleted>false</Deleted> but again this isn't a requirement, we can make this property optional it just makes things slightly more messy.

1

There are 1 best solutions below

1
michael.hor257k On BEST ANSWER

You could do:

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

Or:

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