2016-12-03 66 views
1

對於給定的XSL和XML,我只獲得一行輸出。由於for-each有兩個序列,我預計有兩行輸出?
我錯過了什麼?使用XSLT:爲什麼<for-each>不會迭代兩次

XSL:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    version="2.0"> 
    <xsl:output indent="yes" /> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="/"> 

    <xsl:variable name="pat" as="item()*"> 
     <xsl:sequence select="/myroot[1]/mychild[1]/test[1]/@testing"/> 
     <xsl:sequence select="/myroot[1]/mychild[2]/comment[1]"/> 
    </xsl:variable> 

    <xsl:for-each select="$pat"> 
     <xsl:choose> 
      <xsl:when test=". instance of element()"> 
       <xsl:text>  Node: </xsl:text> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:text>Atomic value: </xsl:text> 
      </xsl:otherwise> 
     </xsl:choose> 
     <xsl:value-of select="."/> 
     <xsl:text>&#xA;</xsl:text> 
    </xsl:for-each> 
    </xsl:template> 

</xsl:stylesheet> 

XML使用:

<?xml version="1.0" encoding="Windows-1252" standalone="no"?> 
<myroot > 
    <mychild id="123"> 
     <fruit>apple</fruit> 
     <test hello="world" testing="removed" brackets="angled" question="answers"/> 
     <comment>This is a comment</comment> 
    </mychild>   
    <mychild id="789"> 
     <fruit>orange</fruit> 
     <test brackets="round" hello="greeting"> 
      <number>111</number> 
     </test> 
     <!-- this is a test comment --> 
     <dates> 
      <modified>123</modified> 
      <created>880</created> 
      <accessed>44</accessed> 
     </dates> 
    </mychild>   
    <mychild id="456"> 
     <fruit>banana</fruit> 
     <comment>This will be removed</comment> 
    </mychild> 
</myroot> 

輸出如下所示。我收到的只有一行。
爲什麼第二個序列沒有顯示任何內容?

<?xml version="1.0" encoding="UTF-8"?> 

原子值:除去

我希望它像下面

<?xml version="1.0" encoding="UTF-8"?> 

原子值給出顯示的內容:刪除
節點:這是一個註釋

+0

你的問題是缺少一個重要的標籤。因爲您正在使用''和''實例',我添加了XSLT-2.0標籤。現在這是一個全新的問題。 – zx485

回答

0

因爲只有選定序列中的一個節點:

  1. /myroot[1]/mychild[1]/test[1]/@testing選擇1個節點
  2. /myroot[1]/mychild[2]/comment[1]選擇0節點

對於#2中,如果要選擇的第一評論節點的第二mychild元素的子而不是第一comment元素(其不存在作爲第二個mychild元素的子元素),則更改

<xsl:sequence select="/myroot[1]/mychild[2]/comment[1]"/> 

<xsl:sequence select="/myroot[1]/mychild[2]/comment()[1]"/> 
+1

當然,如果$ node是一個註釋節點,那麼元素()的$ node實例將爲false。 –

+0

@MichaelKay:沒錯,但是這個條件永遠不會用於評論節點,因爲錯誤的XPath#2不選擇評論節點。 (還有一個'xsl:otherwise',如果存在,它會報告第二次迭代。) – kjhughes