2016-02-12 65 views
2

一個最大值的節點:使用XPath選擇具有給定一個XML文檔這樣的屬性

<node> 
    <node text="text1" x=400 y=400></node> 
</node> 
<node> 
    <node text="text1" x=400 y=900></node> 
</node> 
<node> 
    <node text="text2" x=400 y=1000></node> 
</node> 
... etc ... 

我怎麼會寫一個XPath查詢以選擇文本屬性爲「text1」中的節點y的最大價值(在這種情況下是900)?我不知道y值究竟是什麼,但我知道我總是應該選擇的節點是具有較高y值的節點,並且這兩個節點不會是兄弟節點。除了y值,我試圖區分的兩個節點將具有相同的所有屬性。

回答

3

您的輸入文檔格式不正確。它缺少一個最外層(根)元素,而某些屬性值沒有引號。給定一個結構良好的輸入文件是這樣的:

<root> 
<node> 
    <node text="text1" x="400" y="400"></node> 
</node> 
<node> 
    <node text="text1" x="400" y="900"></node> 
</node> 
<node> 
    <node text="text2" x="400" y="1000"></node> 
</node> 
</root> 

以下XPath表達式:

//node[@text = 'text1' and not(@y < preceding::node[@text = 'text1']/@y or @y < following::node[@text = 'text1']/@y)] 

發現node元件(一個或多個),其具有text1和@y的最高值。在這種情況下,唯一的結果是

<node text="text1" x="400" y="900"/> 

更詳細地,所述路徑表達式意味着

//node            select all `node` elements, anywhere in 
                the document 
[@text = 'text1'         but only if its `text` attribute is 
                equal to "text1" 
and not(@y < preceding::node[@text = 'text1']/@y and only if the value of its `y` 
                attribute is not lower than the value 
                of an `y` attribute of another `node` 
                element of the same sort that precedes 
                the current one 
or @y < following::node[@text = 'text1']/@y)]  and only if the value if its `y` 
                attribute is not lower than the value 
                of an `y` attribute of another `node` 
                element of the same sort that follows 
                the current one 

EDIT:或者,使用

//node[@text="text1" and not(//node[@text="text1"]/@y > @y)] 

如splash58曾建議。這個表達式的語義與上面的非常相似。

+0

好,我只是用手把它們扔在一起。我會給這個解決方案一個鏡頭! –

+0

@ user3174484讓我知道它是否有效。如果沒有,你可能已經省略了一些重要的東西,並且需要顯示更多的實際輸入文檔。 –

+0

它的工作原理,謝謝你! –

相關問題