Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath wildcard in attribute value

I have the following XPath to match attributes of the class span:

//span[@class='amount'] 

I want to match all elements that have the class attribute of "amount" but also may have other classes as well. I thought I could do this:

//span[@class='*amount*']  

but that doesn't work...how can I do this?

like image 257
Colin Brown Avatar asked Dec 23 '11 19:12

Colin Brown


People also ask

Can you use wildcard in XPath?

XPATH allows the use of wildcards to write more robust path expressions where the use of specific path expressions is either impossible or undesirable. matches any element node. matches any attribute node. matches any type of node.

What does the wildcard operator * Do in XPath?

xml file to learn XPath wildcards and its style sheet which uses Xpath expressions to select a value from the elements. The most widely used type is the asterisk(*). To match all nodes below expression is used and the (//) operator denotes a descendant type wildcard.

Can you use wildcards in XML?

There are three wildcards: * , node( ) , and @* . The * does not match attributes, text nodes, comments, or processing-instruction nodes. Thus, in the previous example, output will only come from child elements that have their own template rules that override this one.

What is Asterisk XPath?

We generally use an asterisk (*) while writing XPaths. This is called a Wildcard character. An asterisk in XPath may represent any node or attribute name of XML or DOM. A node is a tag in XML document. When we do not bother about node or attribute name we can use an asterisk.


2 Answers

Use the following expression:

//span[contains(concat(' ', @class, ' '), ' amount ')] 

You could use contains on its own, but that would also match classes like someamount. Test the above expression on the following input:

<root>   <span class="test amount blah"/>   <span class="amount test"/>   <span class="test amount"/>   <span class="amount"/>   <span class="someamount"/> </root> 

It will select the first four span elements, but not the last one.

like image 143
Wayne Avatar answered Sep 19 '22 17:09

Wayne


You need to use contains method. See How to use XPath contains() here?

//span[contains(@class,'amount')]

like image 45
Alexei Levenkov Avatar answered Sep 19 '22 17:09

Alexei Levenkov