2010-11-11 98 views
1

我想從定義爲一個XML文件diplay一組表如下:如何提取「爲eached」元素的子元素,只用XSLT

<reportStructure> 
    <table> 
    <headers> 
     <tableHeader>Header 1.1</tableHeader> 
     <tableHeader>Header 1.2</tableHeader> 
    </headers> 
    <tuples> 
     <tuple> 
     <tableCell>1.1.1</tableCell> 
     <tableCell>1.2.1</tableCell> 
     </tuple> 
     <tuple> 
     <tableCell>1.1.2</tableCell> 
     <tableCell>1.2.2</tableCell> 
     </tuple> 
    </tuples> 
    </table> 
    <table> 
    ... 

我使用XSLT和XPath轉換成數據,但在foreach不工作,我希望它的方式:

 <xsl:template match="reportStructure"> 
     <xsl:for-each select="table"> 
      <table> 
      <tr> 
       <xsl:apply-templates select="/reportStructure/table/headers"/> 
      </tr> 
      <xsl:apply-templates select="/reportStructure/table/tuples/tuple"/> 
      </table>  
     </xsl:for-each> 
     </xsl:template> 

     <xsl:template match="headers"> 
     <xsl:for-each select="tableHeader"> 
      <th> 
      <xsl:value-of select="." /> 
      </th> 
     </xsl:for-each> 
     </xsl:template 

     <xsl:template match="tuple"> 
     <tr> 
      <xsl:for-each select="tableCell"> 
      <td> 
       <xsl:value-of select="." /> 
      </td> 
      </xsl:for-each> 
     </tr> 
     </xsl:template> 

雖然我希望它可以輸出每個表標籤一個表,它輸出的所有表頭和單元格中的每個表標籤。

回答

6

您正在選擇全部您的apply-templates中的標題和元組。

只選擇相關的:

<xsl:template match="reportStructure"> 
    <xsl:for-each select="table"> 
     <table> 
     <tr> 
      <xsl:apply-templates select="headers"/> 
     </tr> 
     <xsl:apply-templates select="tuples/tuple"/> 
     </table>  
    </xsl:for-each> 
    </xsl:template> 

你真的應該也只是有上面作爲一個單一的table模板,無需xsl:for-each

<xsl:template match="table"> 
     <table> 
     <tr> 
      <xsl:apply-templates select="headers"/> 
     </tr> 
     <xsl:apply-templates select="tuples/tuple"/> 
     </table>  
    </xsl:template> 
+0

+1一個去答案。 – 2010-11-11 20:26:48

+0

+1好答案。 – 2010-11-11 20:59:27

2

除了@俄德的很好的答案,這個節目爲什麼「推式」更多...可重用:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="table"> 
     <table> 
      <xsl:apply-templates/> 
     </table> 
    </xsl:template> 
    <xsl:template match="headers|tuple"> 
     <tr> 
      <xsl:apply-templates/> 
     </tr> 
    </xsl:template> 
    <xsl:template match="tableHeader"> 
     <th> 
      <xsl:apply-templates/> 
     </th> 
    </xsl:template> 
    <xsl:template match="tableCell"> 
     <td> 
      <xsl:apply-templates/> 
     </td> 
    </xsl:template> 
</xsl:stylesheet>