Ashwath Prabhu
Ashwath Prabhu

Reputation: 21

How to add OR Condition Inside XPATH of XSLT Template Match

I am in with a requirement for selecting two Values of a Field of 2 Nodes of XSLT.

I need to select the Node A1 and A2 by selecting both CAT and DOG.

Input Looks like this.

<MAIN>
    <A1>
        <B1>CAT</B1>
        <B2>KITTEN</B2>
    </A1>
    <A2>
        <B1>DOG</B1>
        <B2>PUPPY</B2>
    </A2>
    <A3>
        <B1>LION</B1>
        <B2>CUB</B2>
    </A3>
</MAIN>

I am using below Expression:

    <xsl:template match="MAIN[(A1/B1='CAT') or (A2/B1='DOG')]">
    </xsl:template>

This is giving XPATH Expression Error at Runtime.

Also Used below and value was not picked up.

   <xsl:template match="MAIN[A1/B1='CAT' or A2/B1='DOG']">
   </xsl:template>

Upvotes: 2

Views: 873

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 31011

Or operator in XPath is written as | (vertical bar).

To refer to an element containing some text value you should use a predicate, something like [text() = '...'].

So your template can be written as:

<xsl:template match="A1/B1[text() = 'CAT'] | A2/B1[text() = 'DOG']"/>

Note that in the case of an empty template you don't have to write any separate closing tag. It is enough to write <xsl:template .../> as I did above.

Additional remarks

Instead of text() you can write . a dot.

XPath expression A1[B1 = 'CAT'] is also correct, but its meaning is different than above. It refers to:

  • whole A1 element,
  • which has child B1 element with content CAT.

Upvotes: 1

Related Questions