Sometimes, when we are performing an XSLT transformation, we get an empty target element because the source element was not present. If a source element is missing we may want to omit the target element from our output. We often wish to distinguish between a missing element and an empty element. In this recipe, we will show how to distinguish between a missing XML element and an empty XML element in XSLT.
It is possible that the source element might actually be an optional element in the input document, and this will be indicated by the XML element marker within square brackets, as shown in the following example:
Given the following input document:
<inputVariable> <part name="payload"> <ns1:process> <ns1:val1>Only Value</ns1:val1> </ns1:process> </part> </inputVariable>
The previous transform will generate the following output document:
<outputVariable>
<part name="payload">
<processResponse>
<client:val1>Only Value</client:val1>
<client:val2/>
</processResponse>
</part>
</outputVariable>
Note, that this is indistinguishable from the output generated by the following input document:
<inputVariable>
<part name="payload">
<ns1:process>
<ns1:val1>Only Value</ns1:val1>
<ns1:val2></ns2:val2>
</ns1:process>
</part>
</inputVariable>
This may be significant for our future processing, and so we need to be able to distinguish the two input documents, which we do by using an XSLT if
construct.
Open an existing XSLT file that generates an empty element, when an element is not present in the input, to the transform.
if
construct. This makes the target element mapping conditional based on the presence of the missing source element:The if
construct acts as a conditional on any nested mappings underneath it. If the conditional evaluates to true, then the mappings underneath it are executed; otherwise they are ignored, and the elements underneath it will not appear in the output document.
We used the if
construct to test for the existence of an element in the source document, but we could have used it to test any Boolean expression, allowing us to put arbitrary conditional logic in our transform. In this case, rather than mapping an element to the if
construct, we would map an XPath expression using the expression editor.
The MiscMappings
project in the code samples has a sample XSL transformation called CorrectedIntialTransformation.xsl
demonstrating this.