Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath query how to get value of one attribute based on two attribute

Tags:

xml

xpath

I want to extract name attribute value from the following tag

<application
    comments="Do not erase this one"
    executable="run_CIET"
    icon="default"
    instances="1"
    mode="1"
    name="CIET"
    order="10"
    selection="1"
    tool="y"
/>

I can easily get value of name attribute value based on mode value as shown below

xpath Applications.xml '//applications/application[@mode='3']'/@name

But if I want to add more condtion which is "get name attribute value when mode=X and tool attribute is not there in application tag"

How do we do this? I tried something like

xpath Applications.xml '//applications/application[@mode='3' and !@tool]'/@name

but its not working.

I have not used XPath before and I am finding it tricky I search W3C help on XPath but did not find what I wanted. Please help.

like image 525
Umesh K Avatar asked Oct 06 '10 09:10

Umesh K


People also ask

How do I combine two Xpaths?

The | character denotes the XPath union operator. You can use the union operator in any case when you want the union of the nodes selected by several XPath expressions to be returned.

How do I select the second element in XPath?

//div[@class='content'][2] means: Select all elements called div from anywhere in the document, but only the ones that have a class attribute whose value is equal to "content". Of those selected nodes, only keep those which are the second div[@class = 'content'] element of their parent.

How do you write XPath for the same element?

For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.


2 Answers

Using not(@tool) instead of !@tool should do the job. If your XPath engine's not behaving you could conceivably do count(@tool)=0, but that shouldn't be necessary.

like image 77
Flynn1179 Avatar answered Sep 29 '22 12:09

Flynn1179


How do we do this? I tried something like 

    xpath Applications.xml '//applications/application[@mode='3' and !@tool]'/@name

but its not working.



!@tool

is invalid syntax in XPath. There is an != operator, but no ! operator.

Use:

//applications/application[@mode='3' and not(@tool)]/@name 

There are two things you should always try to avoid:

  1. using the != operator -- it has weird definition and doesn't behave like the not() function --never use it if one of the operands is a node-set.

  2. Try to avoid as much as possible using the // abbreviation -- this may cause signifficant inefficiency and also has anomalous behavior that isn't apperent to most people.

like image 35
Dimitre Novatchev Avatar answered Sep 29 '22 14:09

Dimitre Novatchev