Performing a check in XSL
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 chec开发者_StackOverflow中文版kbox 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
<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">
<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.
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>
精彩评论