Happy Bird
Happy Bird

Reputation: 1142

Difference between contains() predicate testing in XPath?

How can one explain the difference between these two XPath expressions?

Expression 1:

//div[contains(@class, 'Test')]

Expression 2:

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

Upvotes: 1

Views: 962

Answers (3)

kjhughes
kjhughes

Reputation: 111541

There is no difference1. In all versions of XPath, including XPath 1.0, both XPaths will select exactly the same set of nodes for all XML documents: All div elements with a @class attribute whose string value contains 'Test'.

Use the first form; it's both shorter and more idiomatic.


1 Unless the XPath being evaluated in the context of a host language that supports XPath 2.0 schema-aware type information -- see Michael Kay's answer.

Upvotes: 3

Michael Kay
Michael Kay

Reputation: 163322

Actually there is a difference, but a very subtle one. If your expression is an XPath 2.0 schema-aware expression, and @class is defined in the schema as list-valued, and if there is more than one item in the list, then //div[contains(@class, 'Test')] will fail with a type error, while //div[@class[contains(.,'Test')]] will return true if and only if one of the items has Test as a substring.

Upvotes: 1

宏杰李
宏杰李

Reputation: 12168

Expression 1:

//div[contains(@class, 'Test')]
  1. current context node is div tag
  2. [] is filter to get special div tag
  3. contains(@class, 'Test') is a string function that return a bool value True or False, it will convert the parameter to its string value. The attribute's string value is its text.so the XPath is: select all the div tag when it's class attribute evaluated to True.

Expression 2:

//div[@class[contains(.,'Test')]]
  1. current context node is div tag
  2. [] is filter to get special div tag
  3. in the filter, the current context node is the attribute node class,

[contains(.,'Test')] will filter the class attribute with string value Test. The left part is //div[filtered class node], so the XPath became: select all the div tag with those filtered class attribute.

Upvotes: 0

Related Questions