2013-12-16 51 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