Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath with multiple conditions

Tags:

xml

xslt

xpath

What XPath can I use to select any category with a name attribute specified and any child node author with the value specified.

I've tried different variations of the path below with no success:

//quotes/category[@name='Sport' and author="James Small"] 

The XML:

<?xml version="1.0" encoding="utf-8"?> <quotes>   <category name="Sport">    <author>James Small<quote date="09/02/1985">Quote One</quote><quote             date="11/02/1925">Quote nine</quote></author>   </category>    <category name="Music">    <author>Stephen Swann  <quote date="04/08/1972">Quote eleven</quote></author>   </category>   </quotes> 
like image 884
mjroodt Avatar asked Apr 20 '12 14:04

mjroodt


People also ask

How do you use multiple XPath?

XPath multiple conditions are used to select multiple attributes, by using XPath in multiple conditions we can select any category with the attribute by specifying child node. We can define the condition in the path when we have to forward the message to more than one interface or more than one receiver.

Can we use and condition in XPath?

Using OR & AND This means that any one condition should be true to find the element. In the below XPath expression, it identifies the elements whose single or both conditions are true. Highlight both elements as 'First Name' element having attribute 'id' and 'Last Name' element having attribute 'name'.

Can we use comparison operators in XPath?

XPath expressions can use comparison operators. Comparison operators compare one value to another. The resulting value is a "boolean" value.


2 Answers

Use:

/category[@name='Sport' and author/text()[1]='James Small'] 

or use:

/category[@name='Sport' and author[starts-with(.,'James Small')]] 

It is a good rule to try to avoid using the // pseudo-operator whenever possible, because its evaluation can typically be very slow.

Also:

./somename 

is equivalent to:

somename 

so it is recommended to use the latter.

like image 32
Dimitre Novatchev Avatar answered Oct 19 '22 08:10

Dimitre Novatchev


Try:
//category[@name='Sport' and ./author/text()='James Small']

like image 172
Cylian Avatar answered Oct 19 '22 08:10

Cylian