Roger Mathis
Roger Mathis

Reputation: 25

xslt Conditional Transformation

I am trying to come up with a xslt that either copies everything from the source xml to target or produce an empty file based on certain value in the source file.

Suppose I have source1.xml, like following:

<Order>
  <isDigitalProduct>true</isDigitalProduct>
  <productID>1234</productID>
<Order>

and source2.xml, like the following:

<Order>
  <isDigitalProduct>false</isDigitalProduct>
  <productID>5678</productID>
<Order>

How can I modify my xslt to evaluate the value of the <isDigitalProduct> so that when its value is "true", copy everything as is, and produce a blank output when its value is "false"? For the example above, source1.xml would have its content copied over, whereas source2.xml after the transformation would produce a blank file.

Any help is appreciated!

One more question, what if instead of copy everything I need to transform the <isDigitalProduct> element into <SerialNumber>. For example, with source2.xml still transforming into empty output while source1.xml be transformed into:

<Order>
  <SerialNumber>ABC</SerialNumber>
  <productID>1234</productID>
<Order>

Thanx!

Upvotes: 0

Views: 661

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 116992

How can I modify my xslt to evaluate the value of the <isDigitalProduct> so that when its value is "true", copy everything as is, and produce a blank output when its value is "false"?

If that's all you want to do, you could do simply:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="utf-8" indent="yes"/>


<xsl:template match="/">
    <xsl:copy-of select="Order[isDigitalProduct='true']"/>
</xsl:template>

</xsl:stylesheet>

One more question, what if instead of copy everything I need to transform the <isDigitalProduct> element into <SerialNumber>.

In such case, instead of copying the complying Order as is, you would apply a template to it - and within that template do any required modifications, for example:

<xsl:template match="/">
    <xsl:apply-templates select="Order[isDigitalProduct='true']"/>
</xsl:template>

<xsl:template match="Order">
    <xsl:copy>
        <SerialNumber>ABC</SerialNumber>
        <xsl:copy-of select="productID"/>
    </xsl:copy>
</xsl:template>

Upvotes: 0

potame
potame

Reputation: 7905

Something like that should work, but you are very likely to get some errors if the resulting tree is empty...

<xsl:template match="Order">
   <xsl:choose>
     <xsl:when test="isDigitalProduct/text() = 'true'">
       <xsl:copy-of select="."/>
     </xsl:when>
     <xsl:otherwise>
     </xsl:otherwise>
   </xsl:choose>
</xsl:template>

Upvotes: 0

Related Questions