2

I am using an XSL when clause to transform one XML file to another XML file. I need to use something like an "exists" function in my when test.

Here's an example source XML:

<People>
    <Person personid="1" location="US" fullname="John Doe"/>
    <Person personid="2" location="US" fullname="Jane Doe"/>
</People>
<Nicknames>
    <Nickname personid="1" nname="Johnny D"/>
</Nicknames>

Here's my example XSL:

  <xsl:element name="HASNICKNAME">
    <xsl:choose>
        <!-- If nickname exists in source XML, return true -->
      <xsl:when test="boolean exists function"
        <xsl:text>TRUE</xsl:text>
      </xsl:when>
      <xsl:otherwise>
        <xsl:text>FALSE</xsl:text>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:element>

Can someone help with the exists part?

cedarleaf
  • 153
  • 1
  • 8
  • possible duplicate of [Check if a node exists using XSLT](http://stackoverflow.com/questions/4694480/check-if-a-node-exists-using-xslt) –  Apr 11 '11 at 21:50
  • Or http://stackoverflow.com/questions/767851/xpath-find-if-node-exists or http://stackoverflow.com/questions/4948878/xslt-detecting-if-a-node-exists or any of http://www.google.com/search?q=site%3Astackoverflow.com+xslt+exist+node –  Apr 11 '11 at 21:57

1 Answers1

2

Suppose the variable $personid contains the @personid of the Person you are checking, then this only checks existence:

<xsl:when test="boolean(//Nickname[@personid=$personid]/@nname)">

For similar issues I normally prefer to check for a non-empty/non-whitespace value:

<xsl:when test="normalize-space(//Nickname[@personid=$personid]/@nname)!=''">

If you use a key like <xsl:key name="nn" match="//Nickname" use="@personid"/>, the following is also possible:

<xsl:when test="normalize-space(key('nn',$personid)/@nname)!=''">

The latter does not need the $personid variable but can directly work with the @personid of the Person you are checking…

mousio
  • 10,079
  • 4
  • 34
  • 43