If you want to write a separate XSL file instead of using the DOM, try the <xsl:if> function. It's format is <xsl:if test="your test here...">XSL code to be processed if test is true</xsl:if>
Here is an example based on your XML (using if in two places, phone ext and middle name:
Code:
<xsl:stylesheet version="1.0" xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform"[/URL] xml:space="preserve">
<xsl:template match="name">
Name: <xsl:value-of select="first"/> <xsl:if test="middle"><xsl:value-of select="middle"/> </xsl:if><xsl:value-of select="last"/></xsl:template>
<xsl:template match="phone">
Type: <xsl:value-of select="@type"/>
Number: (<xsl:value-of select="area"/>)<xsl:value-of select="exchange"/>-<xsl:value-of select="num"/><xsl:if test="ext"> ex. <xsl:value-of select="ext"/></xsl:if></xsl:template>
</xsl:stylesheet>
This is using XSL with a procedural language (apply procedures to data) mindset -- apply the if function to the data. However, XSL is a functional language (not procedural as most of us are familiar with), and it is tied strongly to matching templates. If you want something to be done if the ext element is there, create a template for it. If the element is not there, the template won't be called. Here is a different, template-based XSL file that does the same thing:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform"[/URL] xml:space="preserve">
<xsl:template match="name">
Name: <xsl:apply-templates/></xsl:template>
<xsl:template match="first"><xsl:apply-templates/> </xsl:template>
<xsl:template match="middle"><xsl:apply-templates/> </xsl:template>
<!--<xsl:template match="last"><xsl:apply-templates/></xsl:template>-->
<xsl:template match="phone">
Type: <xsl:apply-templates select="@type"/>
Number: <xsl:apply-templates/></xsl:template>
<xsl:template match="@type"><xsl:value-of select="."/></xsl:template>
<xsl:template match="area">(<xsl:apply-templates/>) </xsl:template>
<xsl:template match="exchange"><xsl:apply-templates/>-</xsl:template>
<!--<xsl:template match="num"><xsl:apply-templates/></xsl:template>-->
<xsl:template match="ext"> ex. <xsl:apply-templates/></xsl:template>
</xsl:stylesheet>
Notice that each template only applies the formatting for that element. Also notice that <xsl:apply-templates> is called to output the text as well. I
should have avoided using a select on my apply-template to call the phone type attribute, since I'm selecting and not relying on pattern matching, but I didn't have time to figure out how to not have it process the entire element tree under phone a second time (producing a second phone number).
Which is best? Depends on what you are most comfortable with. (as is usually the case when asked this question!)