Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

xslt help with optional attribute 1

Status
Not open for further replies.

Kalisto

Programmer
Feb 18, 2003
997
GB
I have an xml element that has an optional attribute of mode. However, when I transform my xml, the end application barfs if this supposedly optional parameter isnt present.

Whats the best way of modifying the xslt, so that if this attribute isnt present, a default is used.

I was thinking of using a seperate template and using With-params. However, if I use

Code:
<xsl:with-param name="mode"><xsl:value-of select="@TextMode" /></xsl:with-param>

and 

<xsl:param name="mode">Default</xsl:param>

Then when the mode attribute isnt present, I get '' passed in, and so what i was hoping would be a default isnt entered.

Am I best off testing the $mode parameter in my template, and if it is null, setting it to a value, or is there a more elegant way of handling this?

Cheers
K
 
Have you tried something like this?
Code:
<xsl:with-param name="mode">
  <xsl:choose>
  <xsl:when test="@TextMode">
    <xsl:value-of select="@TextMode" />
  </xsl:when>
  <xsl:otherwise><xsl:text>Default</xsl:text>
  </xsl:otherwise>
  </xsl:choose>
</xsl:with-param>

Tom Morrison
 
a closely related question...
What if an element is optional?
How can XSTL check for the existence of an element (that can appear 0, 1 or many times in the XML)?
I'm asking this because I typically create a table where each row describes an element, but I want to skip the table all together if no elements are present, otherwise I end up with a table with one row (the main heading).
Hope I explained the problem.
thanks!
andre.
 
Use the XPath function count(). Assuming you are using an xsl:for-each element, you can
Code:
<xsl:if test="count([i]nodeset-for-for-each[/i])">
    <!-- table stuff here -->
    <xsl:for-each select="[i]nodeset-for-for-each[/i]">
      <!-- table row stuff here  -->
    </xsl:for-each>
    <!-- table closing stuff here -->
</xsl:if>
This takes advantage of the conversion of a numeric result to a boolean, where 0-->false and nonzero-->true. If you want to fine tune your table, such as simplifying a table with a single row, you can use an <xsl:choose> structure.

Tom Morrison
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top