2010-07-13 26 views
0

簡而言之,我的問題是我想循環遍歷同一孩子中的一個孩子的內容,但是當我嘗試這樣做時,它遍歷所有內容孩子們,給我的數據和兒童一樣多。在相同的XML子代中爲每個孩子使用XSL

示例代碼:

Input.xml中

<?xml version="1.0"?> 
<base> 
    <item name="item1"> 
     <foo> 
      <type1>1</type1> 
      <type2>2</type2> 
     </foo> 
     <bar> 
      <type3>3</type3> 
     </bar> 
    </item> 
    <item name="item2"> 
     <foo> 
      <type1>4</type1> 
      <type2>5</type2> 
     </foo> 
     <bar> 
      <type3></type3> 
      <!-- NOTE! This value is missing. Therefore we must put a blank value in the table--> 
     </bar> 
    </item> 
    <item name="item3"> 
     <foo> 
      <type1>7</type1> 
      <type2></type2> 
      <!-- NOTE! This value is missing. Therefore we must put a blank value in the table--> 
     </foo> 
     <bar> 
      <type3>9</type3> 
     </bar> 
    </item> 
</base> 

tableMaker.xsl

<?xml version="1.0"?> 

<xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:cyg="http://CygNetSCADA.com/Schemas/CygNetEnterpriseObjects730"> 

    <xsl:output method="html" encoding="UTF-8" /> 

    <xsl:template match="/"> 
     <html> 
      <body> 
       <table border="1"> 
        <tr> 
         <th>Name</th> 
         <xsl:for-each select="base/item/*/*"> 
          <th> 
           <xsl:value-of select="local-name()"/> 
          </th> 
         </xsl:for-each> 
        </tr> 

        <xsl:for-each select="base/item"> 
         <tr> 
          <th> 
           <xsl:value-of select="@name"/> 
          </th> 

          <xsl:for-each select="foo/*"> 
           <xsl:choose> 
            <xsl:when test=".[node()]"> 
             <td> 
              <xsl:value-of select="." /> 
             </td> 
            </xsl:when> 
            <xsl:otherwise> 
             <td /> 
             <!-- This is for that empty value in item3 --> 
            </xsl:otherwise> 
           </xsl:choose> 
          </xsl:for-each> 

          <xsl:for-each select="bar/*"> 
           <xsl:choose> 
            <xsl:when test=".[node()]"> 
             <td> 
              <xsl:value-of select="." /> 
             </td> 
            </xsl:when> 
            <xsl:otherwise> 
             <td /> 
             <!-- This is for that empty value in item2 --> 
            </xsl:otherwise> 
           </xsl:choose> 
          </xsl:for-each> 
         </tr> 
        </xsl:for-each> 
       </table> 
      </body> 
     </html> 
    </xsl:template> 

</xsl:stylesheet> 

在這個例子中,會發生什麼是所生成的HTML有10列 - 一個對於「名稱」和「type1」,「type2」,「type3」三次(對於三個元素爲三次;如果存在在我的輸入中有4個元素,會有3個列)。我只想要「type1」,「type2」和「type3」在列中顯示一次。我該如何去做這件事?

所有幫助表示感謝,並提前致謝!

回答

2

您使用的是XSL 2.0,因此您可以訪問xsl:for-each-group元素。這是你需要在這種情況下:

<tr> 
    <th>Name</th> 
    <xsl:for-each-group select="base/item/*/*" group-by="local-name()"> 
    <th> 
     <xsl:value-of select="current-grouping-key()"/> 
    </th> 
    </xsl:for-each> 
</tr> 
+0

非常好!我對XSLT 2.0的一些元素的理解是不足的。 – 2010-07-13 19:14:29