Sybrentjuhh
Sybrentjuhh

Reputation: 79

XSLT how to test if element has specific name?

I want to test if the name of the attribute contains 'description' (doesn't matter whether it is description1, 2 or 3, as long as the name has description in it) and then use this in for-each cycle. If not, I don't want to show the element. So I have an XML structure like the following:

<item>
 <name>Test xslt</name>
 <code>XSLT</code>
 <description>
  <description1>1x stay</description1>
  <description2>1x breakfast</description2>
  <description3>1x diner</description3>
  <description4>1x free late check-out</description1>
  <address>New York 1234AZ</address>
 </description>
</item>

And then my XSLT would be:

<xsl:for-each select="description">
   <xsl:if test=""> (test here if name cointains description)
     <p><xsl:value-of select="." /></p>
   </xsl:if>
</xsl:for-each>

Now it also shows the element in the array. Does anyone know how to test if the name of element contains specific text and then only show these? Thanks in advance!

Edit:

Fixed the edit already.

Upvotes: 1

Views: 1014

Answers (1)

Siebe Jongebloed
Siebe Jongebloed

Reputation: 4844

This will do without the extra xsl:if

  <xsl:for-each select="//*[contains(local-name(),'description')]">
    <p><xsl:value-of select="." /></p>
  </xsl:for-each>

Like @michael.hor257k in his comment suggests: If you don't use namespace-prefixes and your "description*"-elements always starts with "description" you could make it perform better by using:

  <xsl:for-each select="//*[starts-with(name(),'description')]">
    <p><xsl:value-of select="." /></p>
  </xsl:for-each>

See this answer for explanation difference name() and local-name()

If your context in xslt is the item-element you could also make it work faster like this:

  <xsl:for-each select="descendant::*[starts-with(name(),'description')]">
    <p><xsl:value-of select="." /></p>
  </xsl:for-each>

This site gives you some more help on how xslt works and how the context is changing, i.e. by using xsl:apply-templates or xsl:for-each

Upvotes: 2

Related Questions