karthic
karthic

Reputation: 175

xsl:condition checking

I have an input XML as below

<testing>
<subject ref="yes">
 <firstname>
    tom
 </firstname>
</subject>
<subject ref="no">
 <firstname>
    sam
</firstname>
</subject>
</testing>

I am expecting my output should be.

if the subject has ref as yes. I will get the name value. Else if the ref (no) i won't get element

<testing>
<firstname>
   tom
</firstname>
</testing>

Please guide me here.

Upvotes: 1

Views: 72

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243549

This short transformation:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
  <testing><xsl:apply-templates/></testing>
 </xsl:template>

 <xsl:template match="subject[@ref='yes']">
  <xsl:copy-of select="node()"/>
 </xsl:template>
 <xsl:template match="subject"/>
</xsl:stylesheet>

when applied on the provided XML document:

<testing>
    <subject ref="yes">
        <firstname>
         tom
     </firstname>
    </subject>
    <subject ref="no">
        <firstname>
         sam
     </firstname>
    </subject>
</testing>

produces the wanted, correct result:

<testing>
   <firstname>
         tom
     </firstname>
</testing>

Upvotes: 1

Ankur Ghelani
Ankur Ghelani

Reputation: 659

try this:

<testing>
  <xsl:if test="testing/subject/@ref = 'yes'">
    <firstname>
      <xsl:value-of select="testing/subject/firstname" />
    </firstname>
  </xsl:if>
</testing>

I hope this should work in xslt

Upvotes: 0

Tim C
Tim C

Reputation: 70648

This can be achieved by building on top of the identity transform. Firstly, you would need a template to ignore subject elements with a @ref of 'no'

<xsl:template match="subject[@ref='no']" />

And for subject elements with a @ref of 'yes' you have another template to output just its children

<xsl:template match="subject[@ref='yes']">
   <xsl:apply-templates select="node()"/>
</xsl:template>

In fact, if @ref could only ever be 'yes' or 'no' you could simplify this template match to just <xsl:template match="subject"> as this would match all elements which don't have a @ref of 'no'

Here is the full XSLT

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

   <xsl:template match="subject[@ref='no']" />

   <xsl:template match="subject">
      <xsl:apply-templates select="node()"/>
   </xsl:template>

   <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>

When applied to your sample XML, the following is output

<testing>
<firstname> tom </firstname>
</testing>

Upvotes: 2

Related Questions