xmlxslt-1.0

XSLT Code to extract an element value on basis of a condition


I have below XML where I want to extract the p2 element value for p1 value is Orange using XSLT and then show that value in the variablePrint tag.

<rootyFruity xmlns:h="http://www.w3.org/TR/html4/">
<h:fruit>
    <h:p1>Apple</h:p1>
    <h:p2>1</h:p2>
</h:fruit>
<h:fruit>
    <h:p1>Orange</h:p1>
    <h:p2>2</h:p2>
</h:fruit>
<h:fruit>
    <h:p1>Guava</h:p1>
    <h:p2>3</h:p2>
</h:fruit>
<h:fruit>
    <h:p1>Grapes</h:p1>
    <h:p2>4</h:p2>
</h:fruit>
<h:variablePrint>ssss</h:variablePrint>
</rootyFruity>

Below is the XSLT, I was able to form where I am just grabbing the variablePrint element and displaying value 5 in it using a variable.

Is there a way to extract p2 element value when p1 value is Orange?

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:miscHelper="http://www.jclark.com/xt/java/glog.webserver.util.MiscellaneousHelper"
                version="1.0">
<xsl:variable name="variableName" select="5"/>
    <xsl:output method="xml"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template> 
    <xsl:template match="//*[local-name()='variablePrint']/text()"> 
        <xsl:value-of select="$variableName"/>
    </xsl:template>

</xsl:stylesheet>

Solution

  • You can set the variable this way:

    <xsl:variable name="variableName" select="//h:fruit[h:p1='Orange']/h:p2"/>
    

    That finds the matching fruit element and returns the content of its p2 child. You will need add the definition for the h: namespace prefix.