Sometimes it’s the simple things that make you wonder how they are done on a high level. For example, if you are wondering how you’d match the content of a node in Xpath, you might think to yourself: “Gee I really would like to know which food-nodes in my xml document contain the word ‘Donuts’ – this should be easy to find out with XPath”.
Well, let me save you some time here. At first you might be looking for a function that matches strings. By looking into the w3c xpath function reference you’d find a function called contains(). ‘contains()‘ takes two parameters. And here the fun starts.
What the reference doesn’t tell you (ok I’m sure it does tell you somewhere), is how to fiddle your matches into the first contains() parameter, which incidentally is the text you want to scan. If your document looks something like this:
<mydocument> <food>Bavarian Donuts</food> <food>Cheesecake</food> <food>Oranges</food> </mydocument>
Your first approach might look like this: /mydocument/food[contains(/mydocument/food,'Donuts')] Which, in a universe where everything makes perfect sense, would yield you one hit. However, this one just breaks your XPath processor, because contains() doesn’t accept multiple matches as the first parameter.
Instead you can do this: /mydocument/food[contains(.,'Donuts')]
The trick is that you use the '.' which is a shortcut for the current node function to reference the currently matched node as input to your contains() function. That’s all there’s to it.







