Search code examples
xmlxsltxslt-2.0

Need to select the only one value from multiple element


I need to fetch the only one value from the multiple elements with some conditions

Input XML:

   <PlanMaps>
      <_PlanMaps>
        <PolicyNum>456789</PolicyNum>
      </_PlanMaps>
      <_PlanMaps>
        <PolicyNum>456789</PolicyNum>
      </_PlanMaps>
      <_PlanMaps>
        <PolicyNum>0456789</PolicyNum>
      </_PlanMaps>
    </PlanMaps>

XSLT I tried:

          <IndexField>
                 <idxName>Number</idxName>
                 <idxValue>
                    <xsl:choose>
                       <xsl:when test="PlanMaps/_PlanMaps/PolicyNum[not(starts-with(., '0'))]">
                          <xsl:value-of select="PlanMaps/_PlanMaps/PolicyNum"/>
                       </xsl:when>
                       <xsl:otherwise>
                          <xsl:value-of select="''"/>
                       </xsl:otherwise>
                    </xsl:choose>
                 </idxValue>
              </IndexField>

Output I'm getting

<idxValue>456789 456789 0456789</idxValue>

Expected Output:

<idxValue>456789</idxValue>

Here I have to check the two conditions, one is that if there is having multiple <PolicyNum> having same value the first value should pick and another is if there is having only one <PolicyNum> and its value start with 0 it should be empty.


Solution

  • Taking LMC's answer I think your code could simply be reduced to :

    <IndexField>
      <idxName>Number</idxName>
      <idxValue>
      <xsl:value-of select="(PlanMaps/_PlanMaps/PolicyNum[not(starts-with(., '0'))])[1]"/>
      </idxValue>
    </IndexField>
    

    This will not output anything if there is only one value that starts with zero and will output the first value not starting with zero if there are multiple values.