2016-02-25 81 views
0

我如何可以執行對給定的XML以下查詢:XPATH執行復雜的查詢

  1. 如果(TASK1 = CDE & & TASK2 = ABC)我會得到ID = XYZ-987
  2. IF((TASK1 = ABC & & TASK2 = EFG)||任務5 = NOP),我會得到ID = ABC-123,XYZ-987,RST-567

XML這裏:

<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="task1" operation="and" value="abc" /> 
      <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> 
    <node3> 
     <id>PQR-345</id> 
     <condition> 
      <task name="task1" operation="and" value="ijk" /> 
      <task name="task2" operation="and" value="klm" /> 
      <task name="task8" operation="and" value="jkl" /> 
      <task name="task9" operation="and" value="rst" /> 
     </condition> 
    </node3> 
</node2> 
</node1>  

我想下面的規則,但我得到空的結果

String expression = "/node1/node2/node3/id[following-sibling::condition/task[(@name='task1' and @value='cde') and (@name='task2' and @value='abc')]]" 

我從 How to parse XML using XPATH

會是怎樣表達上述表達對上述兩種情況?

回答

1

爲什麼你的XPath不工作的原因是因爲你的謂詞[(@name='task1' and @value='cde') and (@name='task2' and @value='abc')]相同的任務節點上執行,而如果@name = 'task1'然後@name永遠不能= 'task2'

相反,你應該創建一個將要操作的謂詞/檢查所有這樣的相關節點:

如果(TASK1 = CDE & & TASK2 = ABC)我會得到ID = XYZ-987

/node1/node2/node3[condition/task[@name='task1' and @value='cde'] and condition/task[@name='task2' and @value='abc']]/id

2.

if((task1 = abc & & task2 = efg)||任務5 = NOP),我會得到ID = ABC-123,XYZ-987,RST-567

/node1/node2/node3[condition/task[@name='task1' and @value='abc'] and condition/task[@name='task2' and @value='efg'] or condition/task[@name='task5' and @value='nop']]/id

你可以包括你的括號,如果你想要的,但在布爾運算,and參數總是評估在or參數之前,所以它們在這種情況下是不必要的: /node1/node2/node3[(condition/task[@name='task1' and @value='abc'] and condition/task[@name='task2' and @value='efg']) or condition/task[@name='task5' and @value='nop']]/id

+0

是否有任何有關複雜實例的XPATH的良好教程? –

+0

你也可以回答下面的問題http://stackoverflow.com/questions/35795014/xpath-parsing-issue-with-complex-data –