Reputation: 5266
I want to scan following XML and fetch value of id based on condition name=task2 and value=efg.
<node1>
<node2>
<node3>
<id>ABC-123</id>
<condition>
<task name="task1" operation="and" value="abc" />
<task name="task2" operation="and" value="efg" />
<task name="task3" operation="and" value="hij" />
<task name="task4" operation="or" value="klm" />
<task name="task5" operation="and" value="nop" />
<task name="task6" value="uvw" />
</condition>
</node3>
<node3>
<id>XYZ-987</id>
<condition>
<task name="task1" operation="and" value="cde" />
<task name="task2" operation="and" value="abc" />
<task name="task5" operation="and" value="nop" />
</condition>
</node3>
<node3>
<id>RST-567</id>
<condition>
<task name="task2" operation="and" value="efg" />
<task name="task8" operation="and" value="jkl" />
<task name="task9" operation="and" value="rst" />
<task name="task10" value="xyz" />
</condition>
</node3>
</node2>
</node1>
I am able to scan and get result as count = 2, using
String expression = "//node3/condition/task[@name='"+condition.getKey()+"' and @value='"+condition.getValue()+"']";
But not the value of id using following code
String expression = "//node3/condition/task[@name='"+condition.getKey()+"' and @value='"+condition.getValue()+"']/node3/id";
How to get values "ABC-123" and "RST-567" which would be the correct result?
Referring following blog and w3c links
https://xjaphx.wordpress.com/2011/12/24/android-xml-adventure-parsing-xml-using-xpath/
http://www.w3schools.com/xml/xml_xpath.asp
http://www.w3schools.com/xsl/xpath_operators.asp
Upvotes: 0
Views: 66
Reputation: 89315
You can nest predicates (expression in []
) to achieve that, for example :
//node3[condition/task[@name='task2' and @value='efg']]/id
Upvotes: 1
Reputation: 33000
You can select the ids and filter for the tasks with a following sibling condition:
/node1/node2/node3/id[following-sibling::condition/task[@name='task2' and @value='efg']]
To select only the text values use
/node1/node2/node3/id/text()[../following-sibling::condition/task[@name='task2' and @value='efg']]
Upvotes: 1