hi! i'm relatively new to xpath and im trying to include a search facility in my website which searched through my xml file.

the format of the xml file is as follows:

<years>
   <year>
      <life>
         <title>...title...</title> 
         <full>...full text... </full> 
      </life>
   </year>
   .....
</years>

i need to retrieve all the categories (eg "life") that contain a specific string. at this point the query that i have is: //year/*/*[contains(., '$string')] , which retrieves the inner nodes (title and full). however, if the string is contained in both the title and the full text, the category is returned twice. is there any way to get the parent directory automatically (and only once) if the inner nodes contain the string, or, if found in the title then skip to the next parent directory without going though the full text?

many thanks! anna

You xpath isn't returning the parent at all, it's returning the matching elements with that text. Because multiple elements match the criteria, you get multiple results for each parent element. If you return the parent itself, you'll only get one result:

//year/*/*[contains(., '$string')]/parent::*

you are absolutely right of course :)

I found that this also works: //year/*/*[contains(., '$string')]/.. is there a difference between the two ways of retrieving the parent? tnx

One's more concise, the other is more explicit.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.