Karabatich
Karabatich

Reputation: 11

(//.) Expression in XPath

I have this little problem in getting an XPATH expression result !

Let's say i have this little XML file :

<bookstore>
 <book>
  <title lang="en">Learning Java</title>
  <price>29.99</price>
 </book>

 <book>
  <title lang="en">Learning Xpath</title>
  <price>39.95</price>
 </book>
</bookstore>

What will be the result of :

//book[//.='Lear']

Thank you

Upvotes: 1

Views: 80

Answers (3)

har07
har07

Reputation: 89285

What will be the result of :

//book[//.='Lear']

You can always dump XML sample and xpath expression in an xpath tester and see the result by yourself (f.e using http://www.freeformatter.com/xpath-tester.html, or whatever you like). For the above xpath and XML sample, the result will be nothing. Given that particular XML input, the above xpath expression is the same as //book[false()]. The predicate (content of []) evaluate to false because there is no element containing exact string "Lear".

"But can you tell me what's useful about the dot after the double slash symbol ?"

To answer that comment, see the following break-down :

  • // : Abbreviated syntax for descendant-or-self axis.

  • . : Reference current context node.

  • //. : You can read this as find any node anywhere in the XML document. That can also be expressed as //self::node(). Note that // starts searching from the root element, it doesn't care about current book element being the context.

Upvotes: 1

MarioDS
MarioDS

Reputation: 13063

//book selects all book elements that are descendants of the current context (in your case that would be the root element).

[] indicates a condition to apply to the selection, so in essence you will be filtering book elements.

Inside the square brackets [] the current context becomes book so // means any descendant of book. . simply denotes the element itself which is used here to apply the = operator to. So // means all descendants, //. means "what follows applies to the element which is any descendant`.

Upvotes: 0

OldProgrammer
OldProgrammer

Reputation: 12169

If you are trying to find all books containing title with 'Lear', try this:

//book[contains(title,'Lear')]

Upvotes: 0

Related Questions