tags:

views:

35

answers:

2

Hey

I am trying to perform a check on individual nodes of an XML file, and depending on the contents of a specific node do something, for example if the type is bool display a checkbox or if the type is text display a textarea or a pull down options box.

For example:

<Questions>
<Question>
<Data>What gender are you?</Data>
<Type>pulldown</Type>
</Question>
<Question>
<Data>Do you like Chocolate?</Data>
<Type>checkbox</Type>
</Question>
</Questions>

Thanks in advance

Im not sure if i should be using xsl:choose/xsl:when or xsl:if

+1  A: 

The construct that appears to be most suitable to your needs is xsl:choose:

<xsl:template match="Question">
 <xsl:choose>
  <xsl:when test="Type = 'checkbox'">
      <!-- output checkbox code -->
  </xsl:when>
  <xsl:when test="Type = 'pulldown'">
      <!-- output pulldown code -->
  </xsl:when>
  <xsl:otherwise>
      <!-- output default code -->
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>
Oded
sorry that was just a typo
Uncle
@Dan - fair enough :)
Oded
+4  A: 

<xsl:choose> can and should always be avoided if possible.

This XSLT transformation demonstrates how to process different Question types in a different way without any hardwired conditional logic:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="Question[Type='pulldown']">
   <!-- Implement pull-down here -->
 </xsl:template>

 <xsl:template match="Question[Type='checkbox']">
   <!-- Implement checkbox here -->
 </xsl:template>
</xsl:stylesheet>

<xsl:choose> should be aboided due to the same reason that makes us in OOP avoid the switch(type) statement and use virtual functions instead. This makes the code shorter, reduces the possibility of making an error, is tremendously more extendable and maintainable, supports future code even before it is written.

Dimitre Novatchev
@Dimitre: +1. Yes, "pattern matching" is the way to go with declarative language.
Alejandro
why should xsl:choose be avoided?
Uncle
@Dan: `<xsl:choose` should be aboided due to the same reason that makes us in OOP avoid the `switch(type)` statement and use virtual functions instead. This makes the code shorter, reduces the possibility of making an error, is tremendously more extendable and maintainable, supports future code even before it is written.
Dimitre Novatchev