Sayandip Ghatak
Sayandip Ghatak

Reputation: 303

XPath operator: some child element contains substring

I have a XML file like that :

<?xml version="1.0" encoding="UTF-8"?>
<root> 
  <channel> 
    <item> 
      <title>India Wins</title>  
      <cat>Cricket News</cat>  
      <cat>India</cat> 
    </item>  
    <item> 
      <title>Barcelona Wins</title>  
      <cat>Barcelona</cat>  
      <cat>Celta Vigo</cat>  
      <cat>Football</cat> 
    </item>  
    <item> 
      <title>England lost</title>  
      <cat>Cricket</cat>  
      <cat>T20</cat>  
      <cat>England</cat> 
    </item> 
  </channel> 
</root>

I want to get the all the titles of Cricket News. Like my output should be :India Wins and England lost

So I am running the Xpath Query like that //*[cat="Cricket"]/title It is giving result : England lost, which is understandable to me .

But I want do similar thing like //*[contains(cat,"Cricket")]/title,so that both the titles of the category Cricket and Cricket News will come. But it is giving no output .

Also i have ran the Xpath Query in many online Xpath testers and they are giving error message like that

ERROR - A sequence of more than one item is not allowed as the first argument of contains()

Can anyone tell me how to resolve this ?

Upvotes: 1

Views: 548

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134591

As the error says, the first argument of contains() must not have multiple items. You need to rewrite your xpath to something like this:

//item[cat[contains(.,'Cricket')]]/title/text()

Upvotes: 5

Related Questions