XSLT expression to check if HTML element exists

1.1k Views Asked by At

I am trying to test to see if a HTML element exists within XSLT but cannot get it to work. I am currently trying to assign a variable based on whether it can find it like this:

    <xsl:variable name="TestParaText">  
        <xsl:choose>
            <xsl:when test="contains(smf:body,index[@id='testSpan'])">
                <xsl:value-of select="'Element found'"/>
            </xsl:when>

            <xsl:otherwise>
                <xsl:value-of select="'Element Not Found'"/>                    
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>

Within my HTML I have this:

<span id="testSpan" style="display:none"></span>

I do not want the element to be visible so I have set a style attribute, but I am pretty sure its something to do with my poor xpath / XSLT syntax! Apologies, as I am not very knowledgeable on this topic but hopefully I should of provided enough information for someone to help me. Thanks

HTML Body

2

There are 2 best solutions below

0
On

If below is ur XML

INPUT XML :

<span id="testSpan" style="display:none"></span>

XSL:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="span">
    <xsl:copy>
    <xsl:choose>

    <xsl:when test = "@id = 'testSpan'">            
             <TestParaText>
             Exists
             </TestParaText>
 </xsl:when>
        <xsl:otherwise>
     <TestParaText>
                 Doesnt Exists
     </TestParaText>
        </xsl:otherwise> 
        </xsl:choose>
   </xsl:copy> 
</xsl:template>
</xsl:stylesheet>

OUTPUT will be :

OUTPUT:

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

<span>

<TestParaText>
          Exists
</TestParaText>

</span>

Please share ur request xml and expected OUTPUT

5
On

The contains function works on strings. If you would like to test if smf:body contains a node index[@id='testSpan']. You should have something like this:

<xsl:when test="body[descendant::index[@id='testSpan2']]">