XSLT - select the child of an element where 1 child = 'x' and another child contains 'y'

StackOverflow https://stackoverflow.com/questions/23675183

  •  23-07-2023
  •  | 
  •  

Question

I'm trying to select a particular child element of a row where another child element is equal to a certain value, and another child element contains a value. My XML looks as follows:

<row>
   <field1>HEAD</field1>
   <field2/>
   <field3>123,456,789,000</field3>
   <field4>hello</field4>
   <field5/>
</row>

My goal here is to get the value of <field4/> where <field1/> = HEAD and <field3/> contains '789'.

So far I've tried the following which doesn't seem to work:

<xsl:variable name="myVar" select="789"/>
<xsl:value-of select="row[field1 = 'HEAD' and contains(field3, $myVar)]/field4"/>

Can anyone spot what I'm doing wrong here? Thanks in advance.

Was it helpful?

Solution

Look at your variable setup - it should be select="'789'" if you want to assign the literal '789':

   <xsl:template match="/">
      <xsl:variable name="myVar" select="'789'" />
      <xsl:value-of select="row[field1 = 'HEAD' 
                          and contains(field3, $myVar)]/field4"/>
   </xsl:template>

Edit : To Clarify

  <xsl:variable name="myVar" select="z123" />

Will assign the value of the element z123 (i.e. 789 if the document looked as follows)

<row>
   <z123>789</z123>
   <field1>HEAD</field1>

Whereas

  <xsl:variable name="myVar" select="'z123'" />

Assigns the literal z123. I'm guessing the reason why a raw 789 works is because xml elements cannot start with a number and the parser is assuming a literal instead. See @michael's explanation on WHY the numeric literal works.

OTHER TIPS

I tried your code in the following stylesheet:

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

    <xsl:output indent="yes"/>

    <xsl:variable name="myVar" select="789"/>

    <xsl:template match="/">
        <xsl:value-of select="row[field1 = 'HEAD' and contains(field3, $myVar)]/field4"/>
    </xsl:template>

</xsl:stylesheet>

and it works fine, it outputs hello

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top