2013-12-20 23 views
1

我試圖改變一個xml文檔,看起來像這樣:如何設置全局變量的幾個條件下,XSL

<CData> 
    <Description>whatever</Description> 
    <Property> 
     <SetValue>123</SetValue> 
     <Description>whatever</Description> 
     <DefaultValue>321</DefaultValue> 
    </Property> 
     <Property> 
     <SetValue>999</SetValue> 
     <Description>whatever</Description> 
     <DefaultValue>721</DefaultValue> 
    </Property> 
</CData> 

每個CDATA標記是一個表和財產標籤代表一個錶行。現在我需要檢查每個CDate標籤,如果單個Property標籤有一個Default和一個SetValue,並且它們是不同的。這背後的原因是我只想要DefaultValue和SetValue不同的表。這裏是一個做工精細的檢查:

<xsl:for-each select="CData"> 
    <xsl:for-each select="Property"> 
    <xsl:if test="SetValue"> 
     <xsl:if test="SetValue/text()!=''"> 
     <xsl:if test="DefaultValue"> 
      <xsl:if test="SetValue!=DefaultValue"> 
      //SET a Value 
      </xsl:if 
     </xsl:if> 
     <xsl:if test="not(DefaultValue)"> 
     //SET a VALUE 
     </xsl:if> 
    </xsl:if> 
    </xsl:if> 
</xsl:for-each> 

在此檢查我需要的,如果條件爲真,這for-each循環後,我想用if標籤檢查變量,它被設置變量如果它被設置,我想打印一張表。我現在唯一的問題是我不知道如何在循環中設置一個變量,我可以像全局變量一樣使用它。

回答

2

這不是XSLT的工作方式 - 所有變量都是詞法範圍的,一旦創建變量就無法更改它的值。

你需要思考這個問題有點不同。而是一個循環,通過和試驗條件逐一去,並設置標誌的「程序」的看法,你需要更多的聲明認爲 - 使用謂詞選擇您感興趣的節點:

<!-- this variable will contain only the Property elements that have a SetValue 
    and a DefaultValue that are different --> 
<xsl:variable name="interestingProperties" 
    select="CData/Property[SetValue != DefaultValue]" /> 

和然後採取行動取決於是否選擇任何節點:

<xsl:if test="$interestingProperties"> 
    <table> 
    <xsl:for-each select="$interestingProperties"> 
     <tr>...</tr> 
    </xsl:for-each> 
    </table> 
</xsl:if> 

如果你想允許屬性元素有一個DefaultValue那麼你可以改變謂詞位:

<!-- this variable will contain only the Property elements that have a SetValue 
    and do not also have a DefaultValue which matches it --> 
<xsl:variable name="interestingProperties" 
    select="CData/Property[SetValue][not(SetValue = DefaultValue)]" /> 

這裏我使用的是not(X = Y)而不是X != Y,因爲在處理可能有零個或多個成員的節點集時,語義會稍有不同。本質上SetValue != DefaultValue表示「有一對SetValue和一個DefaultValue元素,使得它們的值不同」(這尤其意味着每個測試必須至少有一個成功),而not(SetValue = DefaultValue)表示「它不是如果存在一對SetValueDefaultValue匹配「(如果SetValueDefaultValue丟失,它可以成功,所以我們還需要單獨的[SetValue]以確保它存在)。

+0

'的' 的工作原理,但有時我有隻是有一個的情況下屬性標記中的SetValue標記,並且沒有DefaultValue標記。在這種情況下的表應打印,以及因爲一個的SetValue是differtent到默認值,因爲它不存在.. – user2435480

+0

'的'! – user2435480

+0

@ user2435480'[DefaultValue or not(DefaultValue)]'是多餘的,因爲它永遠是真的。我用另一個更簡潔的建議編輯了我的答案。 –