2012-05-19 31 views
2

我正在試驗xpath。xpath - if else structure

這裏是XML我使用的實驗:

<moves> 
    <roll player="1">6</roll> 
    <piece nr="1" player="1" field="1"/> 
    <roll player="2">4</roll> 
    <roll player="2">6</roll> 
    <piece nr="5" player="2" field="11"/> 
    <roll player="1">4</roll> 
    <piece nr="1" player="1" field="5"/> 
    <roll player="2">6</roll> 
    <piece nr="5" player="2" field="17"/> 
    <roll player="1">6</roll> 
    <piece nr="2" player="1" field="1"/> 
    <roll player="2">6</roll> 
    <piece nr="6" player="2" field="11"/> 
</moves> 

那麼如何實現的XPath的的if else?

一樣,如果第二個動作是從球員之一,那麼就f.ex .:還給...

更新1:

確定這裏就是我說:

boolean(/game/moves/roll[2]/@player=1 

如果第二個元素是玩家1或不是,那麼現在我想添加一個else-Path,如果它會是?那麼如何補充呢?

+0

我不理解你到底要。另外你到目前爲止已經嘗試過了什麼樣的XPath表達式不適合你,但你期待着工作。 –

+0

好的,這裏是我嘗試過的:boolean(/ game/moves/roll [2]/@ player = 1),這讓我錯誤返回導致播放器不是一個,但如果它將是一個如何插入一個else-Path與一個行動(就像退回)?? – maximus

+0

@ user1248720你見過[this](http://stackoverflow.com/questions/971067/is-there-an-if-then-else-statement-in-xpath)嗎? – keyser

回答

6

使用XPath 2.0表達式像下面

if(/moves/roll[2]/@player eq '1') 
    then 'player: 1' 
    else ('player: ', data(/moves/roll[2]/@player)) 

XSLT 2.0 - 基於驗證:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
<xsl:output method="text"/> 

<xsl:template match="/"> 
    <xsl:sequence select= 
    "if(/moves/roll[2]/@player eq '1') 
     then 'player: 1' 
     else ('player: ', data(/moves/roll[2]/@player)) 
    "/> 
</xsl:template> 
</xsl:stylesheet> 

當這個變換所提供的XML文檔應用:

<moves> 
    <roll player="1">6</roll> 
    <piece nr="1" player="1" field="1"/> 
    <roll player="2">4</roll> 
    <roll player="2">6</roll> 
    <piece nr="5" player="2" field="11"/> 
    <roll player="1">4</roll> 
    <piece nr="1" player="1" field="5"/> 
    <roll player="2">6</roll> 
    <piece nr="5" player="2" field="17"/> 
    <roll player="1">6</roll> 
    <piece nr="2" player="1" field="1"/> 
    <roll player="2">6</roll> 
    <piece nr="6" player="2" field="11"/> 
</moves> 

上面的XPath表達式求值,評價的結果複製到輸出:

player: 2