2013-12-16 54 views
1

我已經在xsl中爲每個循環應用了一個邏輯,但它的行爲不正確。誰能幫我嗎。xsl爲每個循環無法正常工作(邏輯)

XML

<a> 
<b> 
    <c> 
    <string>16</string> 
    <string>4</string> 
    <string>id</string> 
    <int>123</int> 
    </c> 
    <c> 
    <string>16</string> 
    <string>4</string> 
    <string>id</string> 
    <int>123</int> 
    </c> 
</b> 
</a> 

XSL

<xsl:for-each select="https://stackoverflow.com/a/b/c"> 
    <c>  
    <xsl:for-each select="https://stackoverflow.com/a/b/c/string">" 
     <xsl:variable name ="pos" select="position()"/> 
     <xsl:if test="position() mod 2!=0"> 
      <xsl:choose> 
       <xsl:when test="self::node()[text()='16']"> 
        <int>16</int><int>4</int> 
       </xsl:when> 
       <xsl:otherwise> 
        <xsl:element name="{/a/b/c/string[position()=$pos]}">" 
         <xsl:value-of select="https://stackoverflow.com/a/b/c/string[position()=$pos+1]\/> 
        </xsl:element> 
       </xsl:otherwise> 
      </xsl:choose> 
     </xsl:if> 
    </xsl:for-each> 
</c>  </xsl:for-each> 

所需的輸出

<a> 
    <b> 
     <c> 
     <int>16</int> 
     <int>4</int> 
     <id>123</id> 
     </c> 
    <c> 
     <int>16</int> 
     <int>4</int> 
     <id>123</id> 
    </c> 
    </b> 
</a> 

實際輸出

<a> 
<b> 
<c> 
<int>16</int> 
<int>4</int> 
<id>123</id> 
<int>16</int> 
<int>4</int> 
</c> 
<c> 
<int>16</int> 
<int>4</int> 
<id>123</id> 
<int>16</int> 
<int>4</int> 
</c> 
</b> 
</a> 

有一個在內部for-each循環,但我不能找出

+0

你那句你的問題建議的心態的問題的方法。如果一個程序沒有達到你期望的程度,那麼你的期望錯誤的可能性是99.9%。首先說「我犯了一個錯誤」,而不是「程序行爲不正確」,並立即將自己置於正確的位置開始尋找原因。 –

+0

抱歉@MichaelKay,但我寫了xsl爲每個循環不正常工作(邏輯)。無論我在哪裏提到我已經應用了logice,但該邏輯並不符合我的要求,我明確表示它的錯誤僅僅是編的... :)無論如何,我會記住你的建議。 – Pulkit

+0

也許這只是使用英語。該程序根據語言規範正常工作。這並不意味着它正在做你想做的事。 –

回答

4

這是你的內心for-each循環

<xsl:for-each select="https://stackoverflow.com/a/b/c/string"> 

當XPath表達式以「/」,它啓動了一些問題意味着它是一個絕對的表達。 「/」是指頂級文檔節點,它將開始從XML的根部開始選擇事件,而不管您當前在XML中的位置。

你想要的是一個相對錶達式。在點你做你的內心「的,每一個」你的當前上下文爲「C」的元素,所以你需要寫的是這個

<xsl:for-each select="string"> 

這將返回唯一的「串」元素是孩子當前「c」元素。

此外,您當前的xsl:element語句可以更改。相反,這樣做

<xsl:element name="{/a/b/c/string[position()=$pos]}"> 

,你可以簡單地做這

<xsl:element name="{.}"> 

而在這一點上得到以下元素的值,做到這一點。

<xsl:value-of select="following-sibling::*[1]"/> 

試試這個XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output omit-xml-declaration="yes" indent="yes" /> 

    <xsl:template match="/"> 
    <xsl:for-each select="a/b/c"> 
     <c>  
     <xsl:for-each select="string"> 
      <xsl:if test="position() mod 2!=0"> 
       <xsl:choose> 
        <xsl:when test="self::node()[text()='16']"> 
         <int>16</int><int>4</int> 
        </xsl:when> 
        <xsl:otherwise> 
         <xsl:element name="{.}"> 
          <xsl:value-of select="following-sibling::*[1]"/> 
         </xsl:element> 
        </xsl:otherwise> 
       </xsl:choose> 
      </xsl:if> 
     </xsl:for-each> 
     </c> 
    </xsl:for-each> 
    </xsl:template> 
</xsl:stylesheet> 
+0

你對我來說是一個救命的人......它的工作原理是:D – Pulkit