Manisha
Manisha

Reputation: 17

xslt with substring .i am failing in getting correct ouput

I have return XSLT for getting output. Please correct this xslt if any thing is wrong

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<item>
<itemSale>
<xsl:if test="itemSale='abed' and itemsearch='bra'">
<xsl:value-of select="substring(itemSale,1,2)">
</xsl:value-of>
</xsl:if>
</itemSale>
</item>
</xsl:template>
</xsl:stylesheet> 

Output xml I want is

<?xml version="1.0" encoding="UTF-8"?>
<item>
<itemSale>ab</itemSale>
</item>

Input xml for testing

<?xml version="1.0"?>
<item>
<itemSale>abed</itemSale>
<itemsearch>bra</itemsearch>
</item>

but I am getting Output xml as

<?xml version="1.0" encoding="UTF-8"?>
<item>
<itemSale></itemSale>
</item>

Upvotes: 0

Views: 25

Answers (1)

JLRishe
JLRishe

Reputation: 101730

Your template matches / (the document root) and the only child element of that is item. itemSale and itemsearch are not children of the root, so itemSale produces 0 nodes and itemSale = 'abed' will always be false.

The two main options here are:

  1. Match the document element instead (I recommend this):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/*">  <!--  here -->
    <item>
        <itemSale>
            <xsl:if test="itemSale='abed' and itemsearch='bra'">
                <xsl:value-of select="substring(itemSale, 1, 2)" />
            </xsl:if>
        </itemSale>
    </item>
  </xsl:template>
</xsl:stylesheet>
  1. Use the whole paths to your elements:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <item>
        <itemSale>
            <xsl:if test="item/itemSale='abed' and item/itemsearch='bra'">
                <xsl:value-of select="substring(item/itemSale, 1, 2)" />
            </xsl:if>
        </itemSale>
    </item>
  </xsl:template>
</xsl:stylesheet>

Upvotes: 2

Related Questions