2016-03-03 54 views
0

使用下面的XML如何解析和使用XPATH

<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="abc" /> 
      <task name="task2" operation="and" value="efg" /> 
      <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> 

我想ID = XYZ-987的條件名稱=「任務1」,值=「ABC」名稱從XML獲取確切的結果= 「task2」,value =「efg」AND name =「task5」,value =「nop」

我得到2個結果(ABC-123和XYZ-987)而不是1個(XYZ-987)。 使用下面的XPath表達式

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

我怎麼能過濾這些結果2基於輸入條件的大小和如上所述獲得與恰好3個條件的條目?

參考XPATH executing complex queries來開發表達。

回答

1

通過在表達式中追加「和count(條件/任務)= 3」得到答案。

/node1/node2/node3[condition/task[@name='task1' and @value='abc'] and condition/task[@name='task2' and @value='efg'] and condition/task[@name='task5' and @value='nop'] and count(condition/task)=3]/id 
+0

您是不是指'和count(條件/任務)= 3'? – har07

+0

是的,添加計數我得到了結果 –

+0

我的意思是沒有發佈XML中的'事件'元素,但突然你的答案有'計數(條件/事件)'在裏面。這可能會讓未來的訪客感到困惑,你真的認爲它還是它是一個錯字? – har07