Search code examples
xmlxpathxml-parsingxpath-2.0

Select nodes containing a child with a class that contains X


I got the following XML:

  <a> 
    <div class="from ng-binding">Stranger</div>  
    <div class="subject ng-binding">Hello there</div>  
    <div class="time ng-binding"</div> 
  </a>

I'm trying to select the a tag which has a child which class contains "subject" (so basically the a tag of this example).

I have tried the following:

//a[contains(.//div/@class,'subject')]

But it does not select anything. I changed it to //a[contains(.//div/@class,'from')] and that works so I don't get what the issue is. Shouldn't .//check all children of the node?


Solution

  • You want

    //a[.//div[contains(@class, 'subject')]]
    

    The contains() function only takes the first item in its first argument, so if you pass .//div/@class as the first argument to contains(), you will only be testing the first result of .//div/@class instead of testing all of them.

    In other words, the code you tried is essentially equivalent to

    //a[contains((.//div/@class)[1],'subject')]