2010-11-11 101 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>