How to get string length

XML to be used for our example:

<FoodItems>
    <Item>
       <Name>Juice</Name>
    </Item>
    <Item>
        <Name>Bread</Name>
    </Item>
    <Item>
        <Name>Eggs</Name>
    </Item>
<FoodItems>

Now use this xml in xslt as

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="FoodItems">
  <table border="1" style="background-color:#cccc00">
    <tr>
      <th>Food Item</th>
      <th>String Length</th>
    </tr>
    <xsl:for-each select="FoodItems">  
    <tr>
      <td><xsl:value-of select="Name"/></td>
      <td><xsl:value-of select="string-length(Name)"/></td>
      </tr>
    </xsl:for-each>
  </table>
</xsl:template>
</xsl:stylesheet>

 

Output 

FoodItem String Length
Juice 5
Bread 5
Eggs 4

How to access a variable from within xsl:for-each from outside xsl:for-each

You must have used variables in xslt, like how easy it is to use them anywhere.

In the same way you can also wrap xsl: for-each with an xsl: variable.

For example, the following stylesheet declares a variable EmployeeName and within the xsl: for-each it uses xsl: value-of and xsl: text.

All of the text values are assigned to the variable EmployeeName, which is used outside of the xsl: for-each to select it’s value.

We will use the following xml, for example :

xml

 

And here is the code for xslt –

xslt