XSl: Variable - a condition to check if a value exists

Using XSLT 1.0, how to check if a value exists in a variable or not?

I assign a value to a variable from my XML data, and then have to check if it comes out or not:

<xsl:variable name="DOC_TYPE">
  <xsl:value-of select="name(./RootTag/*[1])"/>
</xsl:variable>
<xsl:if test="string($DOC_TYPE) = ''">
  <xsl:variable name="DOC_TYPE">
    <xsl:value-of select="name(./*[1])"/>
  </xsl:variable>
</xsl:if>  

The above does not work properly. I need if in my data exists <RootTag>then the variable must contain the child element below <RootTag>. If <RootTag>not, then DOC_TYPE should be the first tag in my XML data.

Thanks for your reply.

+3
source share
3 answers

You cannot reassign variables in XSLT. Variables are immutable; you cannot change their value. Someday.

, , :

<xsl:variable name="DOC_TYPE">
  <xsl:choose>
    <xsl:when test="RootTag">
      <xsl:value-of select="name(RootTag/*[1])" />
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="name(*[1])" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>

:

  • : './RootTag' . XPath, , , 'RootTag'
  • this: <xsl:value-of select="name(*[1])"/> ( ), <xsl:if test="string($DOC_TYPE) = ''">, <xsl:if test="$DOC_TYPE = ''">
  • , node, XPath test="..." - node -set true
  • XSLT . . (, <xsl:if>) ( </xsl:if>).
+8

   <xsl:variable name="DOC_TYPE">
     <xsl:choose>
       <xsl:when test="/RootTag"><xsl:value-of select="name(/RootTag/*[1])"></xsl:value-of></xsl:when>
       <xsl:otherwise><xsl:value-of select="name(/*[1])"/></xsl:otherwise>
     </xsl:choose>
   </xsl:variable>
+1

It exists only if you have assigned it. There is no reason to test it for existence.

See also here

0
source

Source: https://habr.com/ru/post/1718721/


All Articles