2017-01-08 125 views
3

的XPath:獲取父節點的值鑑於這種XML每個子節點

<child id="1" name="alpha" >Some Text</child 
<child id="2" name="beta" > 
    <grandchild id="2.1"></grandchild> 
    <grandchild id="2.2"></grandchild> 
</child> 
<child id="3" name="gamma" mark="yes" > 
    <grandchild id="3.1" name="gamma-alpha"> </grandchild> 
    <grandchild id="3.2" name="gamma-beta" ></grandchild> 
</child> 

有4個孫子節點,我想獲得所有他們的父母(這恰好是在我的示例數據)id值中的「孩子」節點。我自己的愚蠢的嘗試:

//孫子/父母子女::/@ ID

回報:

text{"2"}, 
text{"3"} 

而已,但

text{"2"}, 
text{"2"}, 
text{"3"}, 
text{"3"} 

是我想看到什麼。

回答

4

您需要使用一臺主機的語言來遍歷grandchild元素和訪問parent::child/@id每個或者你需要移動到的XPath 2.0(https://www.w3.org/TR/xpath20/#id-for-expressions)或更高版本,並使用for $gc in //grandchild return $gc/parent::child/@id或與XPath 3.0(https://www.w3.org/TR/xpath-30/#id-map-operator)或更高版本和使用//grandchild!parent::child/@id。使用XPath,路徑選擇節點中的任何步驟/exp消除了重複項,因此您無法使用/編寫單個表達式來爲您擁有的兩個元素返回四個id屬性。

+0

儘管答案在技術上是正確的,但並不能解釋爲什麼不出現重複。 XPath在節點集上工作,而不是強制性的。根據定義,這些集合不能包含重複項。 – Lucero

+2

好吧,如果XPath只在集合上運行,那麼我的XPath 2.0或3.0建議將不起作用。我解釋說,選擇節點的步驟消除了重複項,這在XPath 2.0和3.0數據模型和規範的意義上是正確的。 XPath 1.0適用於節點集,這是正確的。 –

+0

是的,我應該寫出我的意思是XPath 1.0,謝謝指出它。 – Lucero