Infinitexistence
Infinitexistence

Reputation: 155

XSL "if" statement to not display an element if it is not present

I am developing an RSS manager and various RSS feeds will contain various elements, some may not include these elements. I would like to implement an xsl:if statement to not display an element if it does not exist in the feed.

For example:

<xsl:template match="item"> <!--an item in a feed-->
<xsl:value-of select="title" /> <!--display feed items title-->

<xsl:value-of select="author" />    <!--to display item's author BUT not all feed items have an author-->

How can I make it so that it does not display author info unless that element is present?

Upvotes: 1

Views: 1481

Answers (3)

Michael Kay
Michael Kay

Reputation: 163539

If you use the standard recursive-descent style of XSLT coding, then

<xsl:apply-templates select="author"/>

achieves the required effect: if there is no author, nothing is output.

Upvotes: 3

Rookie Programmer Aravind
Rookie Programmer Aravind

Reputation: 12154

XSL never complains about existance of node, in simple words Do it only if the node is present is taken care by-default.

In the above code, it tries to find <author> node, if found it will copy else ignore.

If you are worried about unnecessary whitespace then use this: (assuming that current node is parent of author)

<xsl:if test='author'>
    <xsl:value-of select="author" />
</xsl:if>

Upvotes: 2

Andreas
Andreas

Reputation: 1250

<xsl:apply-templates select="item[title]"> will use the "item" template only if it conains a "title" element.
@Peter: item/author will not match item with author child but author with item parent
@AlexM: I would prefer not to mimic procedural programming and use the XSLT way instead

Upvotes: 0

Related Questions